本文目录导读:

我来为你详细梳理Java集合框架的调用流程,包括核心接口、实现类及其交互逻辑。
Java集合框架架构
核心接口层次
Collection (接口)
├── List (接口)
│ ├── ArrayList
│ ├── LinkedList
│ └── Vector (已过时)
├── Set (接口)
│ ├── HashSet
│ ├── LinkedHashSet
│ └── TreeSet
└── Queue (接口)
├── LinkedList
└── PriorityQueue
Map (接口)
├── HashMap
├── LinkedHashMap
├── TreeMap
└── Hashtable (已过时)
统一调用流程
1 创建集合对象
// 创建集合(多态方式) List<String> list = new ArrayList<>(); Set<Integer> set = new HashSet<>(); Map<String, Object> map = new HashMap<>();
2 添加元素流程
// 1. 调用add方法
list.add("element");
// 2. ArrayList内部流程
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 扩容检查
elementData[size++] = e; // 尾部添加
return true;
}
// 3. HashMap put流程
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
// 内部putVal方法核心逻辑
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; // 初始化数组
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null); // 无hash冲突
else {
// 处理hash冲突(链表/红黑树)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // 树化
treeifyBin(tab, hash);
break;
}
}
}
}
}
3 遍历集合流程
Iterator模式统一遍历
// 1. List遍历
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
// 2. Set遍历
Set<Integer> set = new HashSet<>();
for (Integer num : set) { // 增强for循环底层也是Iterator
System.out.println(num);
}
// 3. Map遍历(Entry方式)
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
}
4 删除元素流程
// 安全删除(使用Iterator)
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if ("remove".equals(element)) {
iterator.remove(); // 安全删除
}
}
// ArrayList的Iterator.remove()实现
private class Itr implements Iterator<E> {
int cursor; // 下一个元素的索引
int lastRet = -1; // 上一个返回元素的索引
int expectedModCount = modCount;
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet); // 调用ArrayList的remove
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
集合操作统一模板
1 CRUD操作模板
public class CollectionOperationTemplate {
// 1. 批量添加
public static <T> void batchAdd(Collection<T> collection, T... elements) {
Collections.addAll(collection, elements);
}
// 2. 条件删除
public static <T> boolean removeIf(Collection<T> collection,
Predicate<? super T> filter) {
return collection.removeIf(filter);
}
// 3. 集合转换
public static <T> List<T> toList(Collection<T> collection) {
return new ArrayList<>(collection);
}
// 4. 同步包装
public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
return Collections.synchronizedCollection(c);
}
}
2 流式操作(Java 8+)
// 统一流式处理
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// 过滤、映射、收集
List<String> filtered = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());
性能对比与选择
| 操作 | ArrayList | LinkedList | HashSet | HashMap |
|---|---|---|---|---|
| 添加 | O(1)* | O(1) | O(1)* | O(1)* |
| 删除 | O(n) | O(1)** | O(1)* | O(1)* |
| 查找 | O(1) | O(n) | O(1) | O(1) |
| 迭代 | O(n) | O(n) | O(n) | O(n) |
需要hash计算,需要扩容,**需要先找到元素位置
最佳实践建议
1 选择指南
// 1. 需要有序、可重复 → List List<String> orderedList = new ArrayList<>(); // 随机访问多 List<String> linkedList = new LinkedList<>(); // 插入删除多 // 2. 需要唯一、无序 → Set Set<String> uniqueSet = new HashSet<>(); // 基本需求 Set<String> sortedSet = new TreeSet<>(); // 需要排序 Set<String> orderSet = new LinkedHashSet<>(); // 需要保持插入顺序 // 3. 需要键值对 → Map Map<String, Object> hashMap = new HashMap<>(); // 基本需求 Map<String, Object> treeMap = new TreeMap<>(); // 需要排序 Map<String, Object> linkedMap = new LinkedHashMap<>(); // 保持插入顺序
2 线程安全处理
// 1. 使用同步包装
List<String> safeList = Collections.synchronizedList(new ArrayList<>());
// 2. 使用并发集合
ConcurrentHashMap<String, Object> concurrentMap = new ConcurrentHashMap<>();
CopyOnWriteArrayList<String> copyOnWriteList = new CopyOnWriteArrayList<>();
// 3. 使用不可变集合(Java 9+)
List<String> immutableList = List.of("a", "b", "c");
实际应用示例
1 数据聚合处理
public class DataAggregation {
public static void main(String[] args) {
// 统一集合操作
List<Transaction> transactions = getTransactions();
// 分组统计
Map<String, DoubleSummaryStatistics> stats = transactions.stream()
.collect(Collectors.groupingBy(
Transaction::getCategory,
Collectors.summarizingDouble(Transaction::getAmount)
));
// 去重
Set<String> uniqueCategories = transactions.stream()
.map(Transaction::getCategory)
.collect(Collectors.toSet());
// 排序
List<Transaction> sorted = transactions.stream()
.sorted(Comparator.comparing(Transaction::getAmount).reversed())
.collect(Collectors.toList());
}
}
这份统一调用流程涵盖了Java集合框架的核心操作模式,选择适合的集合类型和操作方式能显著提升代码效率和可维护性。