先简单介绍一下扩容的时机:
- hashMap初始化put第一个元素【new HashMap()方式】
- 当链表的长度大于等于8,并且table.length < 64【treeifyBin方法里】
- 当table的大小大于 threshold【putVal方法最下面】
记录一下threshold 的计算:
- 初始化时new HashMap(),第一次resize threshold = DEFAULT_LOAD_FACTOR *DEFAULT_INITIAL_CAPACITY
- 后续扩容:threshold = newThr = oldThr << 1
源码晾出来
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* 翻译一下其中的重点:原table中的数据索引到新的table中,要么保持位置不变,要么位置= oldCap(原表大小) + 原表索引
* 先放一下求余公式:X % 2^n = X & (2^n - 1) (x对2的n次方求余)
* length = 2的n次方
* 原表索引 = (hash的后N位) & (length - 1)
* 新表索引 = (hash的后N+1位) & (length << 1 - 1)
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
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; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr; // new HashMap(int) new 出对象后,第一次初始化数组走这
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // new HashMap() 走这
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; j < oldCap; ++j) {
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;
/**
* 新表的索引是否需要加上原表的大小(hash的倒数第N+1位参与运算,这个时候位置可能就不冲突了)
* 0 不需要 1 需要
**/
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e; // 记录链表一开始的第一个数据
else
hiTail.next = e; //由tail去串联接下来的数据
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;
}