关键点: 存储数据
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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) // 算出存放的位置,p是该位置链表头节点
// 这个位置如果没有node的话直接创建node
tab[i] = newNode(hash, key, value, null);
else {
// 这个位置如果有node的话
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 比较node链表的第一个元素,如果对应上了则把p赋值给e
e = p;
else if (p instanceof TreeNode)
// 用来处理LinkedHashMap,暂时不管
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 遍历查找node链表
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) { 让e为p的next然后去比较e
// 如果p到了结尾就创建一个node
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; // p、e交替往后挪
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value; // 把value更新为e的val
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}