put源码
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)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize源码
final Node<K,V>[] resize() {
// 保存当前数组以及相关参数。下面称为旧数组
Node<K,V>[] oldTab = table
int oldCap = (oldTab == null) ? 0 : oldTab.length
int oldThr = threshold
int newCap, newThr = 0
// 容量扩展的两种情况:旧容量已经达到最大值,就不扩容了,如果没达到,就扩大 1 倍。
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE
return oldTab
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1
}
// 此处代表map尚未初始化(因为容量小于0),故此这两个else都是为新map初始化
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY)
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE)
}
threshold = newThr
@SuppressWarnings({"rawtypes","unchecked"})
// 创新新的数组,并指向它
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]
table = newTab
if (oldTab != null) {
//遍历旧数组,将元素搬迁到新数组中
for (int j = 0
Node<K,V> e
// 释放旧数组的空间
if ((e = oldTab[j]) != null) {
oldTab[j] = null
if (e.next == null) // 当前节点后面没有链表/树,直接插入到新数组
newTab[e.hash & (newCap - 1)] = e
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap)
else { // preserve order
Node<K,V> loHead = null, loTail = null
Node<K,V> hiHead = null, hiTail = null
Node<K,V> next
do {
next = e.next
// 满足e.hash&oldCap=0的元素,其在新旧数组中的索引位置不变
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e
else
loTail.next = e
loTail = e
}
// e.hash&oldCap不等于0的元素,其在新数组中的索引位置是其在旧数组中索引位置的基础上再加上旧数组长度个偏移量
else {
if (hiTail == null)
hiHead = e
else
hiTail.next = e
hiTail = e
}
} while ((e = next) != null)
if (loTail != null) {
loTail.next = null
newTab[j] = loHead
}
if (hiTail != null) {
hiTail.next = null
newTab[j + oldCap] = hiHead
}
}
}
}
}
return newTab
}