Java学习历程十四《工具类之集合》

Java 中的集合

  • 概念
  • 体系结构
  • 实际应用

概念

Java中的集合是一种工具类,可以储存任意数量的具有共同属性的对象。

对比数组?为什么使用集合?

数组解决的问题:存储20名学生的学生信息。 20名长度固定

集合解决的问题:存储商品信息。 数量不定

集合适用于数据长度不定 动态变化的场景

  1. 数量不定
  2. 具备一对一关系
  3. 需要进行数据的增删
  4. 数据重复问题

体系结构

  • Collection
  • Map

Collection: 存储类的对象

Map: 以键值对的形式存储信息

Collection具备的接口

  • List 序列 有序可重复 -> ArrayList
  • Queue 队列 有序可重复 -> LinkedList
  • Set 集 无序不重复 -> HashSet

Map -> HashMap

List
  1. 集合的一个接口 可重复的集合,被称为序列
  2. 可以精确的控制每个元素的插入位置,或者删除某个位置的元素
  3. 实现类 ArrayList LinkedList

ArrayList 存储类似于数组 LinkedList实际上为链表

ArrayList

是一个长度动态增长的数据,在列表尾部插入删除数据是效率最高的,
更适合用于查找和更新元素,ArrayList中的元素是可以为Null的

  1. 在ArrayList中储存字符串信息
package com.dd1;

import java.util.ArrayList;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) {
        // 使用ArrayList输出字符串
        List alist = new ArrayList(); // 开辟一片连续的内存空间
        alist.add("Java"); // 将 java 添加到 idx 0 的空间中
        alist.add("C"); // ...
        alist.add("C++");
        alist.add("Python");
        System.out.println("列表中元素的个数为:" + alist.size());
        // 遍历输出所有的变成序言
        System.out.println("*****************");
        for (int i = 0; i < alist.size(); i++) {
            System.out.println(alist.get(i));
        }
        System.out.println("移除idx1");
//        alist.remove(1);
        alist.remove("C");
        for (int i = 0; i < alist.size(); i++) {
            System.out.println(alist.get(i));
        }
    }
}

在ArrayList中添加自定义类内容

  • 公告管理
    • 添加和显示
    • 指定位置插入
    • 删除
    • 修改

公告类:

  • 编号
  • 标题
  • 创建人
  • 创建时间
  • 构造方法
  • 成员属性的get方法
  • 成员属性的set方法
// 自定义Notice类
package com.dd1;

import java.util.Date;

public class Notice {
    private int id;
    private String title;
    private String creator;
    private Date createTime;

    public Notice(int id, String title, String creator, Date createTime) {
        this.id = id;
        this.title = title;
        this.creator = creator;
        this.createTime = createTime;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCreator() {
        return creator;
    }

    public void setCreator(String creator) {
        this.creator = creator;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

// Main 方法实现
package com.dd1;

import java.util.ArrayList;
import java.util.Date;

public class NoticeTest {
    public static void main(String[] args) {
        // 创建对象
        Notice nt1 = new Notice(1, "Title1", "Admin", new Date());
        Notice nt2 = new Notice(2, "Title2", "Admin", new Date());
        Notice nt3 = new Notice(3, "Title3", "Admin", new Date());
        // 添加公告
        ArrayList ntList = new ArrayList();
        ntList.add(nt1);
        ntList.add(nt2);
        ntList.add(nt3);
        // 显示公告
        System.out.println("公告的内容为:");
        for (int i = 0; i < ntList.size(); i++) {
            Notice nt = (Notice) ntList.get(i);
            System.out.println(i + 1 + ":" + nt.getTitle());
        }

        // 添加公告
        Notice nt4 = new Notice(4, "Title4", "Admin", new Date());
        // 添加到第一条公告的后面
        ntList.add(1, nt4);
        System.out.println("公告的内容为:");
        for (int i = 0; i < ntList.size(); i++) {
            Notice nt = (Notice) ntList.get(i);
            System.out.println(i + 1 + ":" + nt.getTitle());
        }
        // 删除公告
//        ntList.remove(0);
//        ntList.remove(nt4);
//        System.out.println("公告的内容为:");
//        for (int i = 0; i < ntList.size(); i++) {
//            Notice nt = (Notice) ntList.get(i);
//            System.out.println(i + 1 + ":" + nt.getTitle());
//        }
        // 修改公告nt4
        nt4.setTitle("setTitle4");
        ntList.set(1, nt4);
        System.out.println("公告的内容为:");
        for (int i = 0; i < ntList.size(); i++) {
            Notice nt = (Notice) ntList.get(i);
            System.out.println(i + 1 + ":" + nt.getTitle());
        }


    }
}

Set

元素无需且不可重复的集合,称之为集

  • HashSet 哈希集
    • 无序
    • 不重复 允许有一个null
    • 具备良好的存取和查找性能

Set 中没有ArrayList的get方法来取出Set中的元素,要用到迭代器Iterator

  • Iterator接口可以以统一的方式对各种集合元素进行遍历
    • hasNext()方法检测集合中是否还有下一个元素
    • next()方法返回集合中的下一个元素

简单使用

package com.dd2;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class WordDemo {
    public static void main(String[] args) {
        // 将英文单词存放到HashSet中
        Set st = new HashSet();
        st.add("blue");
        st.add("black");
        st.add("yellow");
        st.add("white");
        // 输出
        System.out.println("集合中的元素为:");
        Iterator its = st.iterator();
        // 遍历迭代器并输出元素
        while (its.hasNext()) {
            System.out.print(its.next() + "--");
        }
        // 在集合中插入新单词,由于无序,所以没有索引方式
        st.add("Red");
        // 插入重复元素 无报错,程序不会将重复数据插入到集合中
        st.add("white");
        its = st.iterator();
        // 遍历迭代器并输出元素
        System.out.println("插入Red后的输出结果");
        while (its.hasNext()) {
            System.out.print(its.next() + "--");
        }
    }
}

宠物猫信息管理

需求:

  • 添加和显示宠物猫的信息
  • 查找某只宠物猫的信息并输出
  • 修改宠物吗的信息
  • 删除宠物吗的信息

Cat

package com.dd2;

import java.util.Objects;

public class Cat {
    private String name;
    private Integer month;
    private String species;

    public Cat(String name, Integer month, String species) {
        this.name = name;
        this.month = month;
        this.species = species;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getMonth() {
        return month;
    }

    public void setMonth(Integer month) {
        this.month = month;
    }

    public String getSpecies() {
        return species;
    }

    public void setSpecies(String species) {
        this.species = species;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", month=" + month +
                ", species='" + species + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        // 对象相等 true
        if (this == o) return true;
        // 判断是否为一个对象
        if (!(o instanceof Cat)) return false;
        Cat cat = (Cat) o;
        return Objects.equals(getName(), cat.getName()) &&
                Objects.equals(getMonth(), cat.getMonth()) &&
                Objects.equals(getSpecies(), cat.getSpecies());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getName(), getMonth(), getSpecies());
    }
}

Main方法

package com.dd2;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CatTest {
    public static void main(String[] args) {
        Cat hh = new Cat("hh", 12, "hh1");
        Cat ff = new Cat("ff", 12, "ff1");
        Set<Cat> st = new HashSet();
        st.add(hh);
        st.add(ff);
        Iterator<Cat> its = st.iterator();
        while (its.hasNext()) {
            System.out.println(its.next());
        }
        // 添加属性相同但是地址不同的对象到Set中的时候得考虑equals方法
        Cat hh1 = new Cat("hh", 12, "hh1");
        st.add(hh1);
        its = st.iterator();
        System.out.println("-------");
        while (its.hasNext()) {
            System.out.println(its.next());
        }
        // 查找信息
        Cat hh2 = new Cat("花花2", 2, "hh2");
        st.add(hh2);
        System.out.println("添加hh2后的宠物猫信息");
        its = st.iterator();
        while (its.hasNext()) {
            System.out.println(its.next());
        }
        //
        if (st.contains(hh2)) {
            System.out.println("存在hh2");
        } else {
            System.out.println("不存在hh");
        }
        // 根据属性查找
        boolean flag = false;
        Cat c = null;
        its = st.iterator();
        while (its.hasNext()) {
            c = its.next();
            if (c.getName().equals("花花2")) {
                flag = true;
                break;
            }

        }
        if (flag) {
            System.out.println("找到花花2");
            System.out.println(c);
        } else {
            System.out.println("没找到花花2");
        }
        // 删除  遍历-> 条件 remove
        for (Cat ct : st) {
            if (ct.getName().equals("花花2")) {
                st.remove(ct);
                System.out.println("执行删除");
            }
        }
        for (Cat ct : st) {
            System.out.println(ct);
        }
        // 删除所有 removeAll  st.isEmpty()方法可以判断集合是否为空
    }
}

Map

  • Map 中 以 key-value 的形式储存数据
  • key-value 以Entry类型的对象实例存在
  • 可通过key快速的查找value的值
  • key不允许重复,只能映射一个value

HashMap

  • 基于哈希表的Map接口实现
  • 允许使用null值和null键
  • Entry对象在HashMap中是无序排列的

商品信息

  • id
  • name
  • price

方法

  • 构造
  • set get
  • toString

Good

package com.dd3;

public class Goods {
    private String id;
    private String name;
    private double price;

    public Goods(String id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

Main 方法

package com.dd3;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class GoodsTest {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        // 定义HashMap对象
        Map<String, Goods> gm = new HashMap<String, Goods>();
        // 输入商品
        System.out.println("输入商品:");
        int i = 0;
        while (i < 3) {
            System.out.println("输入第" + (i + 1) + "条商品");
            System.out.println("编号:");
            String nb = console.next();
            // 判断是否存在重复
            if (gm.containsKey(nb)) {
                System.out.println("商品编号重复");
                continue;
            }
            System.out.println("商品名:");
            String gn = console.next();
            System.out.println("价格:");
            double pr = 0;
            try {
                pr = console.nextDouble();

            } catch (java.util.InputMismatchException e) {
                System.out.println("价格必须为数值");
                // 收集出错的next,否则会将错误的next带到下一次循环中
                console.next();
                continue;
            }
            Goods g = new Goods(nb, gn, pr);
            // 将商品信息添加到Map
            gm.put(nb, g);
            i++;
        }
        // 遍历Map
        for (Goods g :
                gm.values()) {
            System.out.println(g);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值