import java.util.HashMap;
public class HashMap{
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)
//若数组为空即未初始化 || 数组长度=0
n = (tab = resize()).length;
//数组自动扩容,默认长度为16
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))))
//以前的哈希值与当前是否= && key的地址是否= || key是否为空 && key是否相同
e = p;
//当存储相同的key时,e存储新节点的地址实现value的更新
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
当节点个数 >= 8个时,构成红黑树(链表不一定转化为红黑树)
treeifyBin(tab, hash);
break;
当节点数 >= 8,且数组长度>=64时,链表会转化为红黑树来存储。
}
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;
}
HashMap 底层存储源码分析
于 2023-01-05 21:18:12 首次发布