| 操作 | Collection/List/Set | Map |
| 添加 | add(e) / add(index, e) | put(k, v) / putIfAbsent(k, v) |
| 獲取 | get(index) (List) | get(k) |
| 刪除 | remove(index) / remove(o) | remove(k) / remove(k, v) |
| 查找 | contains(o) / indexOf(o) | containsKey(k) / containsValue(v) |
| 大小 | size() / isEmpty() | size() / isEmpty() |
| 遍歷 | iterator() / forEach / stream() | keySet() / values() / entrySet() |
泛型與類型安全
// 編譯期類型檢查,避免運行時 ClassCastException
List list = new ArrayList<>();
list.add("hello");
// list.add(123); // 編譯錯誤
// 鉆石語法 JDK 7+
Map map = new HashMap<>();
集合只存引用。基本類型會自動裝箱。對象可變性若改變會影響集合內容 (如作為 Key 的對象修改 hashCode 會導致 Map 查找失效)。
迭代器模式與 fail-fast
Iterator it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.length() < 3) it.remove(); // 唯一安全的刪除方式
}
Iterator 統一遍歷抽象,支持 remove()。
- fail-fast:非併發集合檢測到結構性修改 (非通過 Iterator) 會拋
ConcurrentModificationException,非線程安全保證,僅為早發現 Bug。
數組與集合互轉
// 集合 → 數組
String[] arr = list.toArray(new String[0]);
// 數組 → List (固定長度,不可增刪)
List fixed = Arrays.asList("a", "b", "c");
// 可變 List
List mutable = new ArrayList<>(Arrays.asList(arr));
// 高效複製
System.arraycopy(src, srcPos, dest, destPos, length);
選型決策樹
- 鍵值對 →
Map:併發 → ConcurrentHashMap;有序 → TreeMap;插入序 → LinkedHashMap;通用 → HashMap。
- 單值序列 →
List:隨機訪問多 → ArrayList;頭尾增刪多 → LinkedList/ArrayDeque。
- 去重/唯一性 →
Set:有序 → TreeSet;插入序 → LinkedHashSet;通用 → HashSet。
- 隊列/棧 →
ArrayDeque (雙端隊列/棧首選)。
總結
集合框架以接口抽象數據結構 (ADT),多態實現滿足不同性能需求。理解底層數據結構 (動態數組、鏈表、哈希表、紅黑樹、堆) 的時空複雜度權衡,是高效選型與調優的關鍵。實戰中善用 Collections/Arrays 工具類、Stream API 處理管道,編寫簡潔健壯的代碼。
- 上一篇文章: Java 進階教程:嵌套類與內部類機制深度解析
- 下一篇文章: Java 進階教程:多線程編程核心機制與同步實戰
Copyright ©
程式碼之家 All Rights Reserved