put方法内部调用putVal方法进行添加元素,putVal(hash(key), key, value, false, true)
1、首先判断数组是否为空或则长度是否为0,如果是,则调用resize方法进行扩容
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
2、通过计算出新添加的元素的hash值,定位到数组元素的位置,判断该位置是否存在元素,不存在就直接插入:
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
这里的 p = tab[i = (n - 1) & hash],已经被赋值了,如果不为空的话,这个变量将作为下面判断的依据
3、如果这个位置不为空,进入到else分支,首先判断新添加元素的hash值与将要插入到这个位置的已有元素的hash值以及key值是否相同且key值不为空,如果成立则直接覆盖。
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) //p就是上一个判断被赋值的变量,说明此时的tab这个位置已经有元素 p 存在了
e = p;
4、如果不存在,判断是否是树节点,是树节点,调用putTreeVal方法添加元素
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
5、如果也不是树节点,那么根据3、4的判断可以说明这个位置存在链表,遍历链表
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;
}
5.1、 if ((e = p.next) == null) //这里的p.next == null,成立则说明已经遍历到链表的最后一个节点了,
将新创建的节点添加到链表末尾 p.next = newNode(hash, key, value, null);这也说明了jdk1.8是采用尾插法添加元素的,
if (binCount >= TREEIFY_THRESHOLD - 1),如果成立,调用treeifyBin方法将链表转为红黑树
5.2、if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))),判断链表是否存在相同的key,存在则直接覆盖
6、当数组对应位置存在相同的key值、hash值时,用新put进的值替换旧值,然后返回旧值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
7、跳出所有判断,继续往下执行,判断此时桶中的元素的个数是否大于threshold,threshold = capacity * loadFactor
if (++size > threshold)
resize();
如果大于,就调用resize进行数组扩容。