| 容器 | 底層結構 | 讀取性能 | 寫入性能 | 特點 |
|---|---|---|---|---|
| ArrayList | 動態數組 | 快 O(1) | 慢 O(n) | 隨機訪問優,擴容觸發數組複製 |
| LinkedList | 雙向鏈表 | 慢 O(n) | 快 O(1) | 首尾增刪優,支援 Deque 操作 |
| HashSet/HashMap | 哈希表(數組+鏈表/紅黑樹) | 快 O(1) | 快 O(1) | 無序、唯一鍵,JDK 1.8 引入紅黑樹優化 |
| TreeSet/TreeMap | 紅黑樹 | 中 O(log n) | 中 O(log n) | 有序、支援範圍查詢 |
| LinkedHashSet/Map | 哈希表+雙向鏈表 | 快 O(1) | 快 O(1) | 保持插入/訪問順序 |
集合判斷重複依賴 equals() 方法。若作為 Map 鍵或存入 Set,必須同時重寫 hashCode(),確保:
a.equals(b) == true ⇒ a.hashCode() == b.hashCode()
否則會導致「邏輯相等但哈希不同」,造成元素無法正確查找或去重失效。
ArrayList、LinkedList)HashSet、TreeSet)HashMap、TreeMap)Collection<Object> c = new ArrayList<>();
c.add("hello");
c.add(12); // 自動裝箱 Integer
c.add("lsb");
System.out.println(c.size()); // 3
System.out.println(c); // [hello, 12, lsb] — 內部調用 toString()
Collection<String> c = new HashSet<>();
c.add("hello"); c.add("abc"); c.add("lsb");
Iterator<String> it = c.iterator();
while (it.hasNext()) {
System.out.println(it.next()); // 輸出順序不固定(HashSet 無序)
}
Set<String> c1 = new HashSet<>(Arrays.asList("a","b","c"));
Set<String> c2 = new HashSet<>(Arrays.asList("a","b","d"));
// 交集
Set<String> intersection = new HashSet<>(c1);
intersection.retainAll(c2); // [a, b]
// 並集
Set<String> union = new HashSet<>(c1);
union.addAll(c2); // [d, a, c, b]
對象需實現 Comparable<T> 接口並覆寫 compareTo(T o),才能用於 TreeSet、Collections.sort() 等有序容器/操作。
HashMap(JDK 1.8+ 鏈表轉紅黑樹防退化)TreeMapLinkedHashMap(適合 LRU 緩存實現)ConcurrentHashMap(分段鎖/CAS,高併發優於 Hashtable)foreach 循環中直接 remove() 集合元素 → 使用 Iterator.remove() 或收集待刪除項後批量處理equals/hashCode,且保持一致性new ArrayList<>(1000))減少擴容開銷List<String> list = new ArrayList<>())便於後續替換實現