//put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//hash算法
static final int hash(Object key) {
int h;
// 取key的hashcode值的低16位 和 key的hashcode值的高16位 进行异或操作 。是为了让32位的hashcode值都能够尽可能的参与运算 (h = key.hashCode()) ^ (h >>> 16)
// 异或可以保证在相同的情况下,0,1平均的可能性最大
// >>> 无符号右移,忽略符号位,空位都以0补齐
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// put的具体操作
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//table未初始化或者长度为0,进行扩容操作
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//n 为数组的长度,为偶数。是2的n次幂。 (n - 1) & hash 这步操作是确定元素放在数组对应的索引位置上
if ((p = tab[i = (n - 1) & hash]) == null)
//该位置为空(则新生成节点放入该数组的该索引位置上)
tab[i] = newNode(hash, key, value, null);
else {
//数组该索引位置已经有值了
Node<K,V> e; K k;
//比较数组中的该索引位置的第一个元素(节点)的hash值相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//将第一个元素的值赋值给e,用e来记录
e = p;
else if (p instanceof TreeNode)//hash值不相等,即key不等,并且为红黑树节点的情况,放入树中
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//最后则为链表节点
for (int binCount = 0; ; ++binCount) {//(1.8尾插法)在链表最末插入节点 (1.7)头插法
if ((e = p.next) == null) {//遍历时到达此链表尾部,最后为null
//在链表的尾部插入新节点
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st TREEIFY_THRESHOLD 8
//如果链表的长度到达设定的阈值(默认为8),此时传化为红黑树,也就是链表长度等于7时就会树化
treeifyBin(tab, hash);
break;
}
//判断链表中节点的key值与插入元素的key值是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//跳出循环
break;
p = e;//用户遍历数组该索引位置上的链表,与前面的e = p.next组合,可以遍历链表
}
}
//key已经存在于这个map中了
if (e != null) { // existing mapping for key
//老值
V oldValue = e.value;
//onlyIfAbsent 为false或者老值为null。就会用新值替换旧值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//返回旧值
return oldValue;
}
}
++modCount;
//实际大小大于阈值则进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
97的二进制码为1100001 (也就是h的二进制码为1100001 ),此时h右移16位,0000000.
1100001
0000000
…取异或(相同为0,不同为1)
1100001(仍然为97)
(n-1)& hash
也就是 (16 -1)& 97
0001111
1100001
…与运算
0000001(也就是1,放入数组的1号索引位置)
&运算:两个同时为1,结果为1,否则为0