05 说一下HashMap的put方法的底层实现原理

vvEcho 2024-01-20 14:08:36
Categories: Tags:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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;
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) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize(); //扩容
afterNodeInsertion(evict);
return null;
}

实现原理

  1. 首先put方法接收到key和value时会根据put的key值进行hash运算得到key对应的哈希值
  2. 然后再调用putVal方法
  3. 先是通过获取的哈希值与(数组长度-1)进行与运算得到一个数组下标
  4. 判断此下标位置是不是空着,如果空着,则直接把key和value封装为一个Node对象并存入此数组位置
  5. 如果此下标位置元素非空,说明此位置上存在Node对象,那么则判断该Node对象是不是一个红黑树节点,如果是,则将key和value封装成一个红黑树节点,并添加到红黑树上去,在这个过程还会判断红黑树中是否存在当前key,如果存在则更新相应的value
  6. 如果此位置上的Node对象是链表节点,则将key和value封装为一个链表的节点并插入到链表中去;
  7. 插入到链表后,会判断链表的节点个数是不是超过了8个,如果超过了8个且容量超过64则把当前位置的链表转化为红黑树;
  8. 最后判断当前HashMap的size是否超过阈值,如果超过则进行扩容操作