Map 介面建立鍵值映射關係,是處理關聯資料的核心工具。本文深度解析三大實作類別核心差異、遍歷最佳實踐與排序 Map 應用場景。
| 特性 | Hashtable | HashMap | TreeMap |
|---|---|---|---|
| 底層結構 | 哈希表 | 哈希表(JDK8+ 鏈表+紅黑樹) | 紅黑樹(自平衡二叉搜尋樹) |
| 允許 null | 鍵值均不允許 | 允許一個 null key、多個 null value | 不允許 null key,允許 null value |
| 線程安全 | 同步(效能低) | 非同步(高效能) | 非同步 |
| 順序保證 | 無序 | 無序 | 按鍵自然順序或Comparator排序 |
| 推薦場景 | 舊版代碼兼容 | 單執行緒高頻增刪查 | 需有序遍歷、範圍查詢 |
Map<String, String> map = new HashMap<>();
map.put("name", "taoshihan");
map.put("age", "100");
// 方式一:keySet + get(兩次查找,稍慢)
for (String key : map.keySet()) {
System.out.println(map.get(key));
}
// 方式二:entrySet(推薦,單次查找)
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
// 方式三:forEach (JDK8+)
map.forEach((k, v) -> System.out.println(k + "=" + v));
class Student implements Comparable<Student> {
String name; int age;
public Student(String name, int age) { this.name = name; this.age = age; }
@Override public int compareTo(Student o) {
return Integer.compare(this.age, o.age); // 年齡升序
}
}
Map<Student, String> treeMap = new TreeMap<>();
treeMap.put(new Student("A", 40), "v1");
treeMap.put(new Student("B", 30), "v2");
treeMap.put(new Student("C", 50), "v3");
// 遍歷輸出按 age 升序:B(30) → A(40) → C(50)
for (Student s : treeMap.keySet()) {
System.out.println(s.name + "=" + s.age);
}
ConcurrentHashMapTreeMapLinkedHashMapHashMap精準掌握 Map 家族特性,能讓資料結構選型事半功倍,避免效能陷阱與併發 Bug。