JDK java.util 套件提供完整資料結構實現,核心介面繼承關係:
Collection
├── List // 有序、可重複
│ ├── ArrayList // 動態陣列,隨機存取快
│ ├── LinkedList // 雙向鏈表,首尾增刪快
│ ├── Vector // 同步版 ArrayList
│ └── Stack // 繼承 Vector,LIFO 棧
└── Set // 無序、不可重複
├── HashSet // HashMap 底層
├── LinkedHashSet // 保持插入順序
└── TreeSet // 紅黑樹,有序
Map // Key-Value 映射
├── HashMap // 非同步、允許 null
├── Hashtable // 同步、不允許 null
├── LinkedHashMap // 保持插入/存取順序
├── TreeMap // 紅黑樹,Key 有序
└── WeakHashMap // Weak Reference Key,適合快取
所有實現類必須提供:
Collection 建構子(複製集合)iterator() 方法回傳 Iterator 統一遍歷Iterator<E> it = collection.iterator();
while (it.hasNext()) {
E element = it.next();
// 處理元素
}
| 實現類 | 底層結構 | 隨機存取 | 首尾操作 | 執行緒安全 | 適用場景 |
|---|---|---|---|---|---|
| ArrayList | 動態陣列 | O(1) 快 | O(n) 慢 | 否 | 頻繁隨機存取、少量增刪 |
| LinkedList | 雙向鏈表 | O(n) 慢 | O(1) 快 | 否 | 頻繁首尾增刪、佇列/棧 |
| Vector | 動態陣列 | O(1) | O(n) | 是 | 舊代碼相容,新代碼建議用 Collections.synchronizedList() |
| Stack | 繼承 Vector | - | - | 是 | LIFO 棧操作 |
ArrayList 擴容機制:預設容量 10,擴容 1.5 倍。大量新增前呼叫 ensureCapacity() 可減少擴容開銷。
equals() 判斷重複,最多一個 nullequals() 變化,會破壞 Set 不變量| 實現類 | 同步 | 允許 Null | 順序 | 適用場景 |
|---|---|---|---|---|
| HashMap | 否 | Key/Value 皆可 | 無序 | 高效能通用映射 |
| Hashtable | 是 | 不可 | 無序 | 舊 API,新代碼用 ConcurrentHashMap |
| LinkedHashMap | 否 | 可 | 插入/存取序 | LRU 快取、需順序遍歷 |
| TreeMap | 否 | Key 不可 | Key 自然序/Comparator | 範圍查詢、有序映射 |
| WeakHashMap | 否 | 可 | 無序 | Key 弱引用,適合元資料快取 |
HashMap Key 設計鐵律:必須正確重寫 hashCode() 與 equals(),且 Key 物件放入後不可變更相關欄位。建議用 String、Integer 等不可變包裝類作 Key。
java.util.Collections 提供靜態方法操作集合:
sort(list)、sort(list, comparator)shuffle(list) 隨機打亂reverse(list)fill(list, obj) 全部替換為指定元素copy(dest, src) 覆蓋目標列表前段min/max(collection)、min/max(collection, comparator)indexOfSubList、lastIndexOfSubListrotate(list, distance) 循環位移LinkedList 或 ArrayDeque (JDK 6+ 推薦)LinkedListArrayListHashSet / LinkedHashSetHashMap (單執行緒) / ConcurrentHashMap (多執行緒)TreeMapWeakHashMap / LinkedHashMap + removeEldestEntry