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;
} // 1、数组没有初始化
if ((p = tab[i = (n - 1) & hash]) == null){
tab[i] = newNode(hash, key, value, null);
} // 2、当前槽位为空
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))){
e = p;
} // 3.1 hash碰撞: hash值相等 && key相等
else if (p instanceof TreeNode){
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
} // 3.2 当前槽位上是红黑树,直接加入红黑树
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1){
treeifyBin(tab, hash);
} // 3.3.1.1.1 当前链表上有8个节点时,转化为红黑树
break;
} // 3.3.1.1 加入链表
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
} // 3.3.1 遍历当前链表,把当前节点挂在末尾,如果hash碰撞则直接跳出
} // 3.3 当前槽位上是链表
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null){
e.value = value;
}
afterNodeAccess(e);
return oldValue;
} // 3.4 当hash碰撞后,如果原值为null,则直接替换;如果onlyIfAbsent=false,则直接替换
} // 3、当前槽位上是链表或者红黑树
++modCount;
if (++size > threshold){
resize(); // 4.1 扩容
} // 4 元素个数大于阈值
afterNodeInsertion(evict);
return null;
}
网友评论