源码追踪
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("name","xiaowang");
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果数组为空 就初始化数组,初始化大小为16
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
如果hashcode扰动得到的数组下标没有元素,直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
头节点key和入参key相等 直接覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
头节点是红黑树
else if (p instanceof TreeNode)
e = ((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;
}
相等直接覆盖
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
超过预置 重新扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
图示