public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
// h = key.hashCode() 为第一步 取hashCode值
// h ^ (h >>> 16) 为第二步 高位参与运算
//int 32位 所以h>>>向右位移16位,刚刚好一半
// ^异或运算,相同结果为0,不同为1
//对hashcode的每一位都进行分散计算,不容易重复
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//初始化map时
if ((tab = table) == null || (n = tab.length) == 0)
//调用扩容方法初始化map容量16
n = (tab = resize()).length;
//与hash与运算形同于 取模运算,不过效率更高,确定当前key的索引位置
if ((p = tab[i = (n - 1) & hash]) == null)
//创建一个元素,无链表元素
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//key相同的情况,当前值赋给e
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 {
//新key存入的情况
for (int binCount = 0; ; ++binCount) {
//无hash碰撞的情况
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;
}