本文章基于JDK1.8
上代码
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//table为空或者tab的长度为0,进行初始化操作
if ((tab = table) == null || (n = tab.length) == 0)
//初始值容量是16
n = (tab = resize()).length;
//根据hash值判断p节点是否为空
if ((p = tab[i = (n - 1) & hash]) == null)
//将新节点赋值给tab[i]
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//传入的hash等于p节点的hash且传入的key等于p节点的key
//或者传入的key不为空且key等于k
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//将p赋值给e
e = p;
//p节点是红黑树节点
else if (p instanceof TreeNode)
//将p赋值给e
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//走链表的逻辑
for (int binCount = 0; ; ++binCount) {
//p的下一个节点为空
if ((e = p.next) == null) {
//将新节点赋值给p的下一个节点
p.next = newNode(hash, key, value, null);
//链表长度大于8转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//传入的hash等于e节点的hash且传入的key等于e节点的key
//或者传入的key不为空且key等于k
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//将e赋值给p
p = e;
}
}
//e不等于空
if (e != null) {
// existing mapping for key
V oldValue = e.value;
//onlyIfAbsent取反或者oldvalue为空
if (!onlyIfAbsent || oldValue == null)
//将传入的value赋值给e.value
e.value = value;
//允许 LinkedHashMap 后操作的回调
afterNodeAccess(e);
return oldValue;
}
}
//更改操作次数
++modCount;
//大于临界值
if (++size > threshold)
//扩容
resize();
//允许 LinkedHashMap 后操作的回调
afterNodeInsertion(evict);
return null;
}
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
//是否遍历过红黑树
boolean searched = false;
//如果父节点为空,root就是根节点;如果父节点不为空,root就是子节点
TreeNode<K,V> root = (parent != null) ? root() : this;
//从根节点遍历