概述
HashMap
是 Java 中最常用的集合之一,其底层实现基于哈希表。为了保证其高效性,HashMap
需要在一定条件下进行扩容。本篇文章详细分析 HashMap
的扩容机制,尤其是 Java 1.8 前后的实现差异。
什么是扩容?
扩容是指 HashMap
的容量不足以容纳更多元素时,创建一个更大的哈希表,并将现有元素重新分布到新表中。
扩容的触发条件:
- 当前元素数量超过
HashMap
的阈值(threshold)。 - 阈值 = 容量(capacity) * 负载因子(load factor)。
扩容过程的核心步骤
- 创建新数组:新容量通常是旧容量的两倍。
- 重新散列(rehash):将旧数组中的所有键值对重新分布到新数组。
- 更新元数据:更新容量、阈值等信息。
Java 1.8 前后的实现区别
Java 1.7 的扩容实现
在 Java 1.7 中,HashMap
的底层结构是数组 + 链表,扩容时的操作流程如下:
- 创建一个新数组,其大小是原数组的两倍。
- 遍历旧数组,将每个链表的元素依次移动到新数组中。
- 元素移动时重新计算其哈希值并确定在新数组中的位置。
问题
- 性能瓶颈:链表的逐个迁移需要重新计算哈希值,效率较低。
- 死循环风险:在多线程环境下,扩容过程可能导致链表成环,造成死循环。
Java 1.8 的扩容实现
在 Java 1.8 中,引入了红黑树优化链表的查询效率,同时对扩容过程也做了一些改进:
- 如果链表长度超过阈值(默认8),会将链表转化为红黑树。
- 扩容时,链表中的元素被分为两个部分:
- 低位桶(低哈希值的元素,位置保持不变)。
- 高位桶(高哈希值的元素,移动到新数组的高位索引)。
优势
- 减少重新计算哈希值:通过高位和低位分组避免了完全重新计算哈希。
- 性能更稳定:链表的转红黑树优化了极端情况下的查询性能。
代码示例
Java 1.7 扩容逻辑
以下代码摘自 JDK 1.7 的 HashMap
源码:
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
Entry[] newTable = new Entry[newCapacity];
for (int i = 0; i < oldCapacity; i++) {
Entry<K,V> e = oldTable[i];
if (e != null) {
oldTable[i] = null; // 释放旧链表
do {
Entry<K,V> next = e.next;
int index = indexFor(e.hash, newCapacity);
e.next = newTable[index];
newTable[index] = e;
e = next;
} while (e != null);
}
}
table = newTable;
}
static int indexFor(int h, int length) {
return h & (length-1);
}
Java 1.8 扩容逻辑
以下代码摘自 JDK 1.8 的 HashMap
源码:
final Node<K,V>[] resize() {
Node<K,V>[] oldTable = table;
int oldCapacity = (oldTable == null) ? 0 : oldTable.length;
int newCapacity = oldCapacity << 1;
Node<K,V>[] newTable = (Node<K,V>[])new Node[newCapacity];
threshold = (int)(newCapacity * loadFactor);
table = newTable;
for (int j = 0; j < oldCapacity; ++j) {
Node<K,V> e = oldTable[j];
if (e != null) {
oldTable[j] = null;
if (e.next == null) {
newTable[e.hash & (newCapacity - 1)] = e;
} else if (e instanceof TreeNode) {
((TreeNode<K,V>)e).split(this, newTable, j, oldCapacity);
} else {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
do {
if ((e.hash & oldCapacity) == 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 = e.next) != null);
if (loTail != null) {
loTail.next = null;
newTable[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTable[j + oldCapacity] = hiHead;
}
}
}
}
return newTable;
}
总结
Java 1.7 的扩容特点
- 实现简单,但性能较低。
- 在多线程环境下容易引发问题。
Java 1.8 的扩容特点
- 通过分组处理高低位桶,避免重新计算哈希值。
- 红黑树的引入提升了查询性能,增强了稳定性。
HashMap
的扩容机制是其高效运作的核心。通过对比 Java 1.7 和 1.8 的实现,可以看出 Java 不断优化的设计思路,旨在提高性能并解决实际问题。