集合框架:List、Map、Set 怎么选

数组长度固定,增删别扭。集合框架就是 Java 给你的「可增长容器」。本周只抓三个主角:ListSetMap

一张选型表

需求 用什么 常见实现
有序、可重复、按索引访问 List ArrayList
去重、关心是否存在 Set HashSet
键值对查找 Map HashMap

List:最常用的名单

List<Student> list = new ArrayList<>();
list.add(new Student("小杨", 22));
list.add(new Student("小陈", 21));

for (Student s : list) {
    s.introduce();
}

list.removeIf(s -> s.getName().equals("小陈"));
System.out.println(list.size());

ArrayList 适合:读多、末尾追加多。中间频繁插入删除以后再了解 LinkedList

Set:自动去重

Set<String> tags = new HashSet<>();
tags.add("Java");
tags.add("JVM");
tags.add("Java"); // 无效
System.out.println(tags.size()); // 2

自定义对象放进 HashSet/HashMap 当 key,需要正确实现 equalshashCode(W9 前后会再强化)。

Map:用键找值

Map<String, Integer> scoreMap = new HashMap<>();
scoreMap.put("小杨", 95);
scoreMap.put("小陈", 88);

Integer score = scoreMap.get("小杨");
System.out.println(score);

for (Map.Entry<String, Integer> e : scoreMap.entrySet()) {
    System.out.println(e.getKey() + " => " + e.getValue());
}

查找、统计、缓存,几乎都是 Map 的戏份。

重构:内存版学生管理升级

Student[] 换成 List<Student>,删除会轻松很多:

public class MemoryStudentRepository implements StudentRepository {
    private final List<Student> students = new ArrayList<>();

    @Override
    public void add(Student s) {
        students.add(s);
    }

    @Override
    public void list() {
        students.forEach(Student::introduce);
    }

    public void removeByName(String name) {
        students.removeIf(s -> s.getName().equals(name));
    }
}

本周练习清单

写在最后

集合是日常编码的「默认武器」。先会用,再谈 ArrayList 扩容、HashMap 哈希——那是进阶周的菜。


YoungGc · Eden手记
学习是第一生产力。

posted @ 2026-07-29 11:25  Eden手记  阅读(4)  评论(0)    收藏  举报