Map 介面四大常用實現 — HashMap、Hashtable、TreeMap、LinkedHashMap — 在底層結構、線程安全、迭代順序、效能特徵上差異顯著。本文系統對比五大維度,助您精準選型。
| 實現類 | 核心資料結構 | 特徵 |
|---|---|---|
| HashMap | 陣列 + 鏈表/紅黑樹 (JDK8+) | 雜湊分桶,O(1) 存取,無序 |
| Hashtable | 陣列 + 鏈表 | 同步版 HashMap,歷史遺留 |
| TreeMap | 紅黑樹 (自平衡二元搜尋樹) | 鍵值有序 (自然序/Comparator),O(log N) |
| LinkedHashMap | 繼承 HashMap + 雙向鏈表 | 維護插入順序或存取順序 |
HashMap、TreeMap、LinkedHashMap → 繼承 AbstractMapHashtable → 繼承 Dictionary (舊版抽象類)LinkedHashMap → 繼承 HashMapsynchronized,線程安全但效能低,不推薦新代碼使用Collections.synchronizedMap(new HashMap()) 或併發包 ConcurrentHashMap (JDK5+ 首選)ConcurrentModificationExceptionmap.put(key, newVal)) 不屬結構性修改
Map<K,V> unmodifiable = Collections.unmodifiableMap(originalMap);
// 任何修改操作拋出 UnsupportedOperationException
accessOrder=true 可做 LRU)new HashMap(int initialCapacity) 避免擴容重雜湊,預估大小 * 1.3String、Integer 等不可變且 hashCode() 分布良好的型別