集合框架是 Java 開發中處理資料群組的基石。本文系統梳理 Collection 體系架構,深入解析 List(ArrayList、LinkedList、Vector、Stack)、Set(HashSet、TreeSet、LinkedHashSet)、Map(HashMap、Hashtable、WeakHashMap)的核心原理、適用場景與典型代碼範例,助你精準選型、高效開發。
所有集合類位於 java.util 套件。集合儲存的是物件引用而非物件本身。主要介面關係:
Collection
├── List (有序、可重複)
│ ├── ArrayList
│ ├── LinkedList
│ ├── Vector
│ │ └── Stack
└── Set (無序、不可重複)
├── HashSet
├── TreeSet
└── LinkedHashSet
Map (鍵值對、Key 不重複)
├── HashMap
├── Hashtable
└── WeakHashMap
List<String> list = new ArrayList<>();
list.add("A"); list.add("B");
list.remove(0); // 移除索引 0
for (String s : list) System.out.println(s);
Deque,可作堆疊、佇列使用。LinkedList<String> dll = new LinkedList<>();
dll.addFirst("First"); dll.addLast("Last");
System.out.println(dll.getFirst()); // First
System.out.println(dll.getLast()); // Last
synchronized,執行緒安全但效能較差。Collections.synchronizedList 或 CopyOnWriteArrayList 取代。push/pop/peek/empty/search。ArrayDeque(非同步、效能更好)。Stack<Integer> st = new Stack<>(); st.push(1); st.push(2); System.out.println(st.pop()); // 2
HashMap,依 hashCode() 與 equals() 判重,存取 O(1)。hashCode() 與 equals()。class Student {
int id;
@Override public int hashCode() { return id; }
@Override public boolean equals(Object o) {
return o instanceof Student && ((Student)o).id == this.id;
}
}
Set<Student> set = new HashSet<>();
set.add(new Student(1));
set.add(new Student(1)); // 不會重複加入
Comparable)或自訂 Comparator 排序。class Student implements Comparable<Student> {
int id;
public int compareTo(Student o) { return this.id - o.id; }
}
Set<Student> ts = new TreeSet<>();
ts.add(new Student(5)); ts.add(new Student(1));
// 迭代輸出:1, 5
Map<String, String> map = new HashMap<>();
map.put("Zara", "8"); map.put("Mahnaz", "31");
for (Map.Entry<String, String> e : map.entrySet())
System.out.println(e.getKey() + "=" + e.getValue());
synchronized,不允許 null Key/Value。ConcurrentHashMap 取代。Map<Integer, byte[]> cache = new WeakHashMap<>();
for (int i = 0; i < 10000; i++)
cache.put(i, new byte[i]); // 記憶體不足時自動清理
// Iterator 遍歷
Iterator<E> it = collection.iterator();
while (it.hasNext()) { E e = it.next(); }
// 增強 for 迴圈
for (E e : collection) { ... }
// ListIterator (僅 List) 支援雙向、增刪
ListIterator<E> lit = list.listIterator();
| 需求 | 推薦實現 | 備註 |
|---|---|---|
| 高效隨機存取、少增刪 | ArrayList | 預設首選 |
| 頻繁頭尾增刪、佇列/堆疊 | LinkedList / ArrayDeque | ArrayDeque 非同步更快 |
| 執行緒安全 List | CopyOnWriteArrayList | 讀多寫少 |
| 去重、無序 | HashSet | 需正確實作 hashCode/equals |
| 去重、自動排序 | TreeSet | 元素需可比較 |
| 去重、保持插入序 | LinkedHashSet | |
| 鍵值對、高效查找 | HashMap | 預設首選 |
| 執行緒安全 Map | ConcurrentHashMap | 高並發首選 |
| 自動清理快取 | WeakHashMap | Key 為弱引用 |
理解各集合底層資料結構、執行緒安全性、效能特徵,才能在實際專案中做出最佳選擇。日常開發以 ArrayList、HashMap、HashSet 為主力,特殊場景再引入 ConcurrentHashMap、TreeSet、WeakHashMap 等進階實現。