基于JDK1.8研读HashMap——put()源码总结
HashMap的put方法源码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
由此可见HashMap的put方法是调用了putVal(),因此再来看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;
//1.如果table是null,或者table长度是0,即代表没有元素,调用resize()方法扩容
if ((tab = table) == null || (n = tab.length) == 0)
//扩容
n = (tab = resize()).length;
//2.i = (n - 1) & hash 计算数组索引i,如果数组是null,即没有Hash冲突,直接插入到此
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//3.如果Hash冲突,则走下面代码
else {
Node<K,V> e; K k;
//(1)如果key的hash和计算得到的hash相等并且key也相等
// 判断key相等用了equals(),因此key为对象时要重写该对象equals()
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//直接覆盖
e = p;
//(2)继续判断插入的数据结构是红黑树还是链表
// 是红黑树,则直接在树中插入或者更新键值对
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 否则,为链表,则在链表中插入或者更新键值对
else {
// I.遍历tab[i],tab[i]下一个元素是null,也就是遍历完毕,则直接插入,
// 当长度大于等于TREEIFY_THRESHOLD - 1时,将链表转为红黑树
// TREEIFY_THRESHOLD - 1 = -1时,代表1.
// II.当key重复时,结束循环,到循环外更新值,并返回旧值.
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;
}
}
// 步骤 II 的后续操作,更新值,返回旧值.
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//插入成功后,判断实际键值对数量 > 最大容量
//调用resize()方法扩容
if (++size > threshold)
resize();
//插入成功时调用此方法,默认实现是null
afterNodeInsertion(evict);
return null;
}