JDK 8 HashMap 详解及详细源码展示
JDK 8 的 HashMap
是 Java 集合框架中的核心实现,基于 哈希表 + 链表 + 红黑树 的复合结构,提供了高效的键值对存储和查询。本文结合源码剖析其设计哲学、核心实现及性能优化技术。
一、核心设计目标:时间复杂度 O(1) 的存取
1.1 哈希冲突解决
- 链表法:哈希冲突时,通过链表(
Entry
链)解决。 - 红黑树优化:当链表长度超过阈值(
TREEIFY_THRESHOLD = 8
)时,链表转为红黑树,将最坏时间复杂度从 O(n) 优化到 O(log n)。
1.2 动态扩容
- 负载因子:默认
loadFactor = 0.75
,当元素数量超过capacity * loadFactor
时,触发扩容。 - 容量翻倍:扩容后容量为原来的 2 倍(
newCap = oldCap << 1
)。
二、源码核心类结构
// java.util.HashMap.java
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
// 默认初始容量(必须是 2 的幂)
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 16
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转红黑树的阈值
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 哈希桶数组
transient Node<K,V>[] table;
// 元素数量
transient int size;
// 修改次数(用于快速失败机制)
transient int modCount;
// 扩容阈值
int threshold;
// 负载因子
final float loadFactor;
// 哈希桶节点(链表节点)
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
K key;
V value;
Node<K,V> next;
}
// 红黑树节点
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent;
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev;
boolean red;
}
}
三、核心方法源码解析
3.1 put
方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 1. 初始化哈希桶数组(懒加载)
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 2. 计算索引,处理哈希冲突
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 3. 键已存在,替换值
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 4. 键不存在,遍历链表/树
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 5. 链表转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 6. 元素数量超过阈值,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
3.2 get
方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 1. 计算索引
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
// 2. 检查头节点
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 3. 遍历链表/树
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(this, tab, hash, key);
do {
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
3.3 resize
方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 1. 计算新容量和阈值
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
newCap = oldCap << 1;
newThr = oldThr << 1;
} else if (oldThr > 0)
newCap = oldThr;
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 2. 创建新哈希桶数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 3. 迁移数据
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
} else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
四、关键优化技术
4.1 哈希计算优化
- 扰动函数:通过
hash = key.hashCode() ^ (hashCode >>> 16)
减少哈希冲突。 - 位运算:使用
(n - 1) & hash
计算索引,替代取模运算,提升性能。
4.2 扩容优化
- 增量迁移:扩容时仅迁移部分数据,避免全量复制。
- 树化/去树化:根据链表长度动态转换数据结构。
4.3 内存局部性
- 链表顺序:新节点插入到链表尾部,提升缓存命中率。
- 红黑树平衡:保持树的高度平衡,减少遍历时间。
五、线程不安全性
5.1 典型问题
- 数据覆盖:多线程
put
时,可能导致键值对丢失。 - 死循环:扩容时多个线程操作链表,可能形成环形链表。
5.2 示例代码
// 线程不安全示例
Map<String, String> map = new HashMap<>();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
for (int i = 0; i < 10000; i++) {
map.put("key" + i, "value" + i);
}
});
executor.submit(() -> {
for (int i = 0; i < 10000; i++) {
map.put("key" + i, "value" + i);
}
});
executor.shutdown();
// 最终 map.size() 可能小于 10000
六、总结
JDK 8 的 HashMap
通过哈希表、链表、红黑树的复合结构,实现了高效的键值对存取。其源码实现深刻体现了数据结构与算法的精髓:
- 哈希冲突解决:通过链表和红黑树动态转换,平衡时间和空间复杂度。
- 动态扩容:容量翻倍策略减少频繁扩容开销。
- 内存局部性:优化数据布局,提升缓存命中率。
实际开发中,建议优先使用 HashMap
,但在多线程场景下需改用 ConcurrentHashMap
或通过 Collections.synchronizedMap
包装。深入理解其源码,有助于设计高性能的 Java 应用程序。