HashMap 到底怎么扩容的?源码级链路拆解
面试官最爱问的集合类,没有之一。本文从 hash 计算到扩容迁移,把 HashMap 的每一步都拆开看。
一、HashMap 的数据结构
JDK 8 的 HashMap 本质是 数组 + 链表 + 红黑树 的复合结构:
scss
┌─────────────────────────────────────────────────────────┐
│ HashMap 内部结构 │
├─────────────────────────────────────────────────────────┤
│ │
│ table[] (Node数组) │
│ ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┐ │
│ │ 0 │ 1 │ 2 │ 3 │ 4 │ ... │ n-1 │ │
│ └──┬──┴─────┴──┬──┴─────┴──┬──┴─────┴─────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │ Node │ │ Node │ │ Node │ │
│ └──┬───┘ └──┬───┘ └──┬───┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │ Node │ │ Node │ │ TreeNode (红黑树) │
│ └──┬───┘ └──────┘ └──────┘ │
│ │ │
│ ▼ │
│ ┌──────┐ │
│ │ Node │ (链表长度 ≥ 8 且 table ≥ 64 时转红黑树) │
│ └──────┘ │
│ │
└─────────────────────────────────────────────────────────┘
核心字段:
java
// 默认初始容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 16
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认负载因子 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转红黑树阈值
static final int TREEIFY_THRESHOLD = 8;
// 红黑树退化为链表阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 转红黑树时 table 最小容量要求
static final int MIN_TREEIFY_CAPACITY = 64;
二、Hash 计算:为什么扰动函数要异或高位?
HashMap 的 hash 方法并非直接用 key.hashCode(),而是做了一次"扰动":
java
static final int hash(Object key) {
int h;
// 高 16 位异或低 16 位
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
为什么要异或高位?
桶定位公式是 index = (n - 1) & hash。当 n = 16 时,n - 1 = 15,二进制是 0000 0000 0000 0000 0000 0000 0000 1111,只有低 4 位参与运算。如果不做扰动,高位的信息完全被丢弃,冲突概率大增。
yaml
hash 扰动过程示例:
hashCode: 1010 1101 0110 0101 0011 1010 1110 1001
↓
h >>> 16: 0000 0000 0000 0000 1010 1101 0110 0101
↓ XOR
hash: 1010 1101 0110 0101 1001 0111 1000 1100
这样高位和低位都参与了桶定位,减少了哈希碰撞。
三、put 方法全链路
put 方法是 HashMap 的核心入口,完整链路如下:
java
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. table 为空或长度为 0,触发初始化(resize)
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 {
// 5. 链表遍历
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// 尾插法
p.next = newNode(hash, key, value, null);
// 链表长度 ≥ 8,尝试转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
break;
}
// 链表中找到相同 key,跳出
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 6. 存在相同 key,替换旧值
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e); // LinkedHashMap 回调
return oldValue;
}
}
++modCount;
// 7. 超过阈值,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict); // LinkedHashMap 回调
return null;
}
用流程图表示:
scss
┌──────────────┐
│ put(k, v) │
└──────┬───────┘
▼
┌──────────────────┐ 是 ┌──────────────┐
│ table 为空? │────────▶│ resize() │
└──────┬───────────┘ └──────────────┘
│ 否
▼
┌──────────────────────┐ 是 ┌────────────────┐
│ 桶位置为空? │────────▶│ 直接放入新 Node │
└──────┬───────────────┘ └────────────────┘
│ 否
▼
┌──────────────────┐ 是 ┌────────────────────┐
│ 第一个节点匹配? │────────▶│ 记录引用准备替换 │
└──────┬───────────┘ └────────────────────┘
│ 否
▼
┌──────────────────┐ 是 ┌────────────────────┐
│ 红黑树节点? │────────▶│ putTreeVal() │
└──────┬───────────┘ └────────────────────┘
│ 否
▼
┌──────────────────────┐
│ 遍历链表,尾插法插入 │
│ 链表长度≥8? 转红黑树 │
└──────┬───────────────┘
▼
┌──────────────────┐ 是 ┌──────────────┐
│ size > threshold? │────────▶│ resize() │
└──────────────────┘ └──────────────┘
四、链表转红黑树:为什么是 8?
treeifyBin 方法并不会直接转红黑树,它先检查 table 容量:
java
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// table 长度 < 64 时,优先扩容而不是树化
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
// 链表 → TreeNode → 红黑树
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
为什么阈值是 8? HashMap 源码注释给出了数学解释:
Ideally, under random hashCodes, the frequency of nodes in bins follows a Poisson distribution with a parameter of about 0.5 on average for the default resize threshold of 0.75.
桶中节点数遵循泊松分布,参数 λ ≈ 0.5:
| 桶中节点数 | 概率 |
|---|---|
| 0 | 0.6065 |
| 1 | 0.3033 |
| 2 | 0.0758 |
| 3 | 0.0126 |
| 4 | 0.0016 |
| 5 | 0.00016 |
| 6 | 0.000013 |
| 7 | 0.0000009 |
| 8 | 0.00000006 |
8 个节点的概率约为 千万分之六,在正常 hash 分布下几乎不会发生。选 8 是一个极端情况的兜底,避免偶发冲突导致链表过长。
退化为链表的阈值是 6 而非 7,是为了避免在 7 和 8 之间频繁振荡。
五、扩容机制:resize 全链路
resize 是 HashMap 最复杂的操作,涉及初始化和扩容两种场景:
java
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// ===== 场景一:扩容(oldCap > 0)=====
if (oldCap > 0) {
// 已达最大容量,不再扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 容量翻倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // 阈值翻倍
}
// ===== 场景二:带初始阈值初始化 =====
else if (oldThr > 0)
newCap = oldThr;
// ===== 场景三:默认初始化 =====
else {
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 创建新数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// ===== 数据迁移 =====
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 {
// 低位链(原位置)和高位链(原位置 + oldCap)
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 关键判断:hash & oldCap == 0 → 低位链
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// hash & oldCap != 0 → 高位链
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;
}
// 高位链放原位置 + oldCap
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
扩容迁移的精妙之处
扩容时 HashMap 不需要重新计算每个元素的 hash,而是利用一个巧妙的位运算:
ini
扩容前: index = hash & (oldCap - 1) // 如 hash & 15
扩容后: index = hash & (newCap - 1) // 如 hash & 31
由于 newCap = oldCap * 2,新增的有效位就是 oldCap 对应的那一位
只需判断: hash & oldCap == 0 ?
例: oldCap = 16 (0001 0000)
hash = 20 (0001 0100) → hash & oldCap = 16 ≠ 0 → 高位链,新位置 = j + 16
hash = 19 (0001 0011) → hash & oldCap = 0 → 低位链,新位置 = j (不变)
less
旧数组 (容量16): 新数组 (容量32):
┌───┬───┬───┬───┬───┐ ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ │ A │ │ B │ │ │ │ A │ │ B │ │ │ A'│ │ B'│ │
└───┴───┴───┴───┴───┘ └───┴───┴───┴───┴───┴───┴───┴───┴───┘
j=1 j=3 j=1 j=3 j=17 j=19
A (hash&oldCap==0) → 原位置 j=1 A' (hash&oldCap≠0) → j+oldCap = 17
B (hash&oldCap==0) → 原位置 j=3 B' (hash&oldCap≠0) → j+oldCap = 19
六、加载因子为什么是 0.75?
加载因子是空间和时间的折中:
| 加载因子 | 空间利用率 | 冲突概率 | 扩容频率 |
|---|---|---|---|
| 0.5 | 低(50%就扩容) | 极低 | 高 |
| 0.75 | 适中 | 较低 | 适中 |
| 1.0 | 高(100%才扩容) | 高 | 低 |
0.75 是源码注释中明确说明的:在时间和空间成本上取得了良好折中。同时 0.75 保证 capacity * loadFactor 是整数(因为 capacity 是 2 的幂次方,0.75 = 3/4,2^n * 3/4 一定是整数)。
七、并发问题:为什么 HashMap 线程不安全?
1. JDK 7 的死循环(头插法导致)
JDK 7 扩容时使用头插法,多线程并发扩容会导致链表成环:
java
// JDK 7 扩容迁移(简化)
void transfer(Entry[] newTable) {
for (Entry<K,V> e : table) {
while (e != null) {
Entry<K,V> next = e.next;
int i = indexFor(e.hash, newTable.length);
e.next = newTable[i]; // 头插法
newTable[i] = e;
e = next;
}
}
}
ini
线程1: 执行到 e=A, next=B 时被挂起
线程2: 完成扩容,B→A(头插法导致链表反转)
线程1 恢复:
e=A, next=B → 将 A 插入新数组
e=B, next=A(因为线程2已经反转了链表)→ 将 B 插入
e=A, next=B(A.next=B)→ 死循环!
A ⇄ B 形成环
2. JDK 8 的数据覆盖
JDK 8 改为尾插法解决了死循环,但仍有并发问题:
java
// 两个线程同时 put,桶位置都为空
// 线程1: tab[i] = newNode(...) ← 还未写入
// 线程2: tab[i] = newNode(...) ← 覆盖线程1的数据
3. size 计数非原子
java
++size; // 非原子操作,并发下计数不准
| 并发问题 | JDK 7 | JDK 8 |
|---|---|---|
| 扩容死循环 | 有(头插法) | 无(尾插法) |
| 数据覆盖 | 有 | 有 |
| size 不准 | 有 | 有 |
| 遍历 ConcurrentModificationException | 有 | 有 |
八、常见面试追问
Q1:HashMap 的 key 可以是 null 吗?
可以。HashMap 对 null key 单独处理,hash 值固定为 0,永远放在桶 index=0 的位置。
Q2:为什么容量必须是 2 的幂次方?
- 桶定位用位运算
(n - 1) & hash替代取模hash % n,性能更高 (n-1)的二进制全是 1,保证 hash 的每一位都参与定位- 扩容时只需判断
hash & oldCap一位即可确定迁移位置
Q3:HashMap 和 Hashtable 的区别?
| 对比项 | HashMap | Hashtable |
|---|---|---|
| 线程安全 | 否 | 是(synchronized) |
| null key/value | 允许 | 不允许 |
| 初始容量 | 16 | 11 |
| 扩容倍数 | 2 倍 | 2n+1 |
| 继承关系 | AbstractMap | Dictionary |
| 性能 | 高 | 低(全表锁) |
Q4:自定义对象作为 key 需要做什么?
必须同时重写 hashCode() 和 equals()。两个方法必须满足:
- equals 相等的对象,hashCode 必须相等
- hashCode 相等的对象,equals 不一定相等
- equals 不等的对象,尽量让 hashCode 不等(减少冲突)
九、总结
HashMap 的核心设计思想可以用一句话概括:用空间换时间,用位运算换性能,用树化兜底极端情况。
关键链路回顾:
bash
put: hash扰动 → 桶定位 → 空桶直接放/非空遍历链表或树 → 尾插法 → 检查树化 → 检查扩容
get: hash扰动 → 桶定位 → 遍历链表或树 → 返回value
扩容: 容量翻倍 → hash&oldCap分流 → 低位链原位置/高位链原位置+oldCap
理解了这些链路,HashMap 相关的面试题就能对答如流了。