Collection (介面)
├── List (有序、可重複、有索引)
│ ├── ArrayList (動態數組,查快增刪慢,非線程安全)
│ ├── LinkedList (雙向鏈表,增刪快查慢,非線程安全)
│ └── Vector (同步 ArrayList,線程安全,效能低)
│
└── Set (無序、不可重複、無索引)
├── HashSet (HashMap 底層,非線程安全)
├── LinkedHashSet (維護插入順序)
└── TreeSet (紅黑樹,自然序/Comparator 排序,非線程安全)
Map (介面,Key-Value,Key 唯一)
├── HashMap (數組+鏈表/紅黑樹,Key/Value 可 null,非線程安全)
├── LinkedHashMap (維護插入/訪問順序)
├── Hashtable (同步 HashMap,Key/Value 不可 null,線程安全)
├── TreeMap (紅黑樹,Key 有序,Key/Value 不可 null,非線程安全)
└── ConcurrentHashMap (分段鎖/CAS,高併發首選)
| 集合 | 底層結構 | 線程安全 | 有序性 | Null 支持 | 典型場景 |
|---|---|---|---|---|---|
| ArrayList | 動態數組 | 否 | 插入序 | 支援 | 隨機訪問多、末尾增刪 |
| LinkedList | 雙向鏈表 | 否 | 插入序 | 支援 | 頻繁頭尾增刪、佇列/棧 |
| HashMap | 數組+鏈表/樹 | 否 | 無序 | Key/Value 可 null | 通用 KV 存儲、緩存 |
| TreeMap | 紅黑樹 | 否 | Key 自然序 | Key/Value 不可 null | 範圍查詢、有序遍歷 |
| ConcurrentHashMap | Node[]+CAS/synchronized | 是 (高併發) | 無序 | Key/Value 不可 null | 多線程環境共享 Map |
hashCode() 確定桶位置。equals() 比較內容。hashCode() 相等且 equals() 為 true → 認定重複。契約:equals() 相等 ⇒ hashCode() 必須相等。違反會導致集合異常 (如放入 Set 後無法找到)。
compareTo() (實現 Comparable) 或 Comparator.compare()。0 → 認定相等 (Key 重複)。public class CollectionDemo {
public static void main(String[] args) {
// 1. List 去重 (保留順序)
List list = Arrays.asList("a", "b", "a", "c", "b");
List distinct = list.stream().distinct().collect(Collectors.toList());
// 或 LinkedHashSet
List distinct2 = new ArrayList<>(new LinkedHashSet<>(list));
System.out.println("List 去重: " + distinct); // [a, b, c]
// 2. Map Key 覆蓋行為
Map map = new HashMap<>();
map.put("name", "張三");
map.put("name", "李四"); // 覆蓋
System.out.println("Map 覆蓋: " + map.get("name")); // 李四
// 3. Set 添加重複元素
Set set = new HashSet<>();
System.out.println(set.add("A")); // true
System.out.println(set.add("A")); // false (未添加)
// 4. TreeMap 自動排序
Map sorted = new TreeMap<>();
sorted.put("c", 3); sorted.put("a", 1); sorted.put("b", 2);
System.out.println("TreeMap 順序: " + sorted.keySet()); // [a, b, c]
}
}
Map 家族。
ConcurrentHashMapTreeMapLinkedHashMapHashMapCollection 家族。
HashSetLinkedHashSetTreeSetArrayListLinkedList
// List 去重並排序
list.stream().distinct().sorted().collect(toList());
// List 轉 Map (Key 提取器, Value 提取器, 衝突合併函數)
Map idUserMap = users.stream()
.collect(toMap(User::getId, u -> u, (v1, v2) -> v1));
// 分組統計
Map cityCount = users.stream()
.collect(groupingBy(User::getCity, counting()));
new ArrayList<>(expectedSize)。new ArrayList<>(Arrays.asList(...))。