/**
* Implements Map.put and related methods.
*
* @param hash key的hash值
* @param key the key
* @param value the value to put
* @param onlyIfAbsent 如果为 true, 不改变存在的value
* @param evict 如果为false,则该表处于创建模式.
* @return 前一个值,如果没有,则为空
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
HashMap.Node<K, V>[] tab; //临时节点
HashMap.Node<K, V> p;
int n, i;
//判断当前hash表是否是空,如果为空,进行扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//扩容后饭后hash表大小
//判断当前桶位置是否为空并且将值赋值于p,减一的原因是因为数组下标从0开始
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
HashMap.Node<K, V> e;
K k;
//判断当前桶节点和新节点的key的hash值和key值是否相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//不相同是否为红黑树节点
else if (p instanceof HashMap.TreeNode)
e = ((HashMap.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;
}
//如果存在判断key是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//到此处该节点已经插入到map中
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//该变量是指HashMap修改了多少次
++modCount;
//插入新数据后判断是否需要扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}