HashMap_resize
2022-07-07 本文已影响0人
kele2018
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;
} // 1.1 容量大于等于1<<30,则修改阈值为Integer.MAX_VALUE
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY){
newThr = oldThr << 1; // double threshold
} // 1.2 容量扩大一倍后 小于 1<<30 && 旧的容量大于等于16,把阈值扩大一倍
} // 1 旧数组的容量大于0 说明数组已经初始化
else if (oldThr > 0){
newCap = oldThr;
} // 2 数组没有初始化且阈值大于0 说明没用空参构造 initial capacity was placed in threshold
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 0.75 * 16
} // 3 数组没有初始化并且阈值等于0 说明第一次初始化数组用了空参构造
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
} // 4 新的阈值为空
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // 创建node数组
table = newTab; // hashMap的使用场景是单线程场景,所以不用考虑在put的时候,get会怎么样
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;
} // 5.1.1.1 当前槽位上只有一个节点,直接迁移到新的数组
else if (e instanceof TreeNode){
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
} // 5.1.1.2 当前槽位上是红黑树,把当前树分成两棵树,前一棵在当前槽位,后一棵在原来槽位加上原来的容量
else {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
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;
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;
}
} // 5.1.1.3 当前槽位上是链表 把链表分成两段,前一段原来槽位,后一段在原来槽位加上原来的容量
} // 5.1.1 当前槽位不为空
} // 5.1 遍历旧数组
} // 5 迁移数据
return newTab;
}