跳到主要内容
版本:Next

集合框架

数组长度固定、功能有限,Java 集合框架提供了更强大的容器。核心是三个接口:List、Set、Map。

体系一览​

接口特点常用实现类
List有序、可重复、按下标访问ArrayList、LinkedList
Set无序、不可重复HashSet、TreeSet(有序)
Map键值对,键唯一HashMap、TreeMap(按键排序)

集合只能存放引用类型,基本类型要用包装类(Integer、Double 等)。

ArrayList:动态数组​

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();

list.add("apple"); // 尾部添加
list.add(0, "banana"); // 指定位置插入
list.get(0); // 读取:"banana"
list.set(1, "orange"); // 修改
list.remove(0); // 删除
list.size(); // 元素个数(注意是方法)
list.contains("orange"); // 是否包含
list.isEmpty(); // 是否为空

for (String fruit : list) { // 遍历
System.out.println(fruit);
}

ArrayList 底层是数组,查询快、中间插删慢;LinkedList 底层是链表,首尾插删快、随机访问慢。绝大多数场景用 ArrayList。

HashSet:去重​

import java.util.HashSet;

HashSet<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(1); // 重复元素不会加入
System.out.println(set.size()); // 2
System.out.println(set.contains(2)); // true

HashMap:键值对​

import java.util.HashMap;

HashMap<String, Integer> scores = new HashMap<>();

scores.put("Alice", 90); // 添加/覆盖
scores.get("Alice"); // 90
scores.getOrDefault("Bob", 0); // 键不存在时给默认值,避免 null
scores.containsKey("Alice"); // true
scores.remove("Alice");
scores.size();

// 遍历键值对
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}

// 只遍历键或值
for (String name : scores.keySet()) { ... }
for (Integer score : scores.values()) { ... }

选择建议​

  • 存一串有序数据,按下标操作 → ArrayList
  • 需要去重、只关心"在不在" → HashSet
  • 需要"键 → 值"的快速查找 → HashMap
  • 要求排序 → TreeSet / TreeMap