put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
点击putVal进入如下代码:
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)刚开始构建一个HashMap时,底层并没有创建数组。而是在第1次put时,才会走resize()的逻辑去创建1个长度16的数组。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
2)&操作,实现了取模的效果。并且位运算,性能比取模高很多。
i = (n - 1) & hash
3)如果寻址到对应的index上为空,则直接创建一个节点放在这个位置上即可。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
为何每次扩容都要2的n次幂
这是现在hashmap优化后的效果。数组刚开始的初始值,以及每次扩容的值,都是2的n次方,16、32、64。因为只要满足这个条件,就可以保证,一个数对(n - 1) 做与运算,和其对n取模效果一样。
put操作的总结
1)对key计算hashcode值
2)对hashcode值无符号右移16位,再与hashcode值做异或运算,得到hash算法结果
3)判断数组是否为空,第1次put时,数组是为空的,这时put前需要初始化一个长度为16(默认)的数组。
4)将hash算法的结果与(n-1)做与运算,定位到数组的某个index
5)判断该index是否为null,如果为null则创建一个节点,放在index这个位置上。