寒假打卡10-1月3日
Java HashMap 源码解析——put、get 方法的底层逻辑
HashMap
是 Java 集合框架中最常用的数据结构之一,它基于哈希表实现,具有快速的查找和插入性能。在本篇文章中,我们将详细解析 HashMap
的源码,特别是其 put
和 get
方法的底层逻辑。
HashMap 的基本结构
HashMap
由数组和链表(或红黑树)组成。数组中的每个元素称为桶(Bucket),每个桶存储一个链表或红黑树。当发生哈希冲突时,元素会被存储在同一个桶中,以链表或红黑树的形式存在。
HashMap 的重要字段
transient Node<K, V>[] table; // 存储元素的数组
transient int size; // HashMap 中的键值对数量
transient int modCount; // 结构修改次数,用于迭代器快速失败
int threshold; // 阈值,决定是否需要扩容
final float loadFactor; // 负载因子
put 方法解析
put
方法用于向 HashMap
中添加键值对。如果键已经存在,则更新其对应的值;如果键不存在,则插入新的键值对。
put 方法的主要步骤
- 计算哈希值:通过
hash(key)
方法计算键的哈希值。 - 定位桶:通过
(n - 1) & hash
计算桶的索引。 - 遍历链表或红黑树:检查键是否已经存在,如果存在则更新值。
- 插入新节点:如果键不存在,则创建新节点并插入链表或红黑树中。
- 扩容检查:检查是否需要扩容,如果需要则进行扩容。
源码解析
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K, V>[] tab; Node<K, V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K, V> e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
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);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
在上述代码中,putVal
方法首先检查并初始化 table
数组,然后根据哈希值定位桶的索引。如果桶为空,则直接插入新节点;如果桶不为空,则遍历链表或红黑树,检查键是否已经存在。如果键存在,则更新其值;如果键不存在,则插入新节点。
get 方法解析
get
方法用于根据键从 HashMap
中获取对应的值。如果键存在,则返回对应的值;如果键不存在,则返回 null
。
get 方法的主要步骤
- 计算哈希值:通过
hash(key)
方法计算键的哈希值。 - 定位桶:通过
(n - 1) & hash
计算桶的索引。 - 遍历链表或红黑树:查找键对应的节点,并返回其值。
源码解析
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;
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K, V>) first).getTreeNode(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;
}
在上述代码中,get
方法首先通过 hash(key)
计算哈希值,然后调用 getNode
方法定位节点。getNode
方法通过哈希值定位桶的索引,并遍历链表或红黑树查找键对应的节点,最后返回节点的值。
扩容机制
当 HashMap
中的键值对数量超过阈值时,需要对 table
数组进行扩容。扩容的过程包括:
- 创建新数组:创建一个容量是原数组两倍的新数组。
- 重新散列:将原数组中的节点重新散列到新数组中。
源码解析
final Node<K, V>[] resize() {
Node<K, V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 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; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
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;
@SuppressWarnings({"rawtypes","unchecked"})
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 { // preserve order
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;
}
在上述代码中,resize
方法首先计算新数组的容量和阈值,然后创建新数组,并将原数组中的节点重新散列到新数组中。
总结
通过解析 HashMap
的 put
和 get
方法源码,我们可以深入理解其底层逻辑和实现原理。HashMap
通过哈希表实现,具有快速的查找和插入性能。它采用链表和红黑树处理哈希冲突,并通过扩容机制动态调整数组大小,以保持高效的性能。
希望通过本篇文章,大家对 Java HashMap
的底层实现有了更深入的了解。在接下来的文章中,我们将继续探讨更多关于 Java 集合框架的知识点,敬请期待!