详解resize()
装填因子(load factor)
装填因子(load factor)决定何时对散列表进行再散列
如果装填因子默认为0.75 并且表中超过75%的位置已经填入元素
也就是说 如果表的长度是16当添加第16*0.75+1个元素时 也就是表中元素的个数超过达临界值时 表将会进行resize()操作 这个表就会用双倍额的桶数自动地再进行散列
这里的双倍是自动转换为下一个二次幂函数的数
*
/**
* 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.
* 初始化或加倍表格大小。
* 如果为null,则分配符合字段阈值中保存的初始容量目标。
* 否则,因为我们使用的是2次幂扩展,所以每个bin中的
* 元素必须保持相同的索引,或者在新表中以2的偏移量移动
* @return the table
*/
final Node<K,V>[] resize() {
//threshold表示要调整大小的下一个值
//将之前的table 保存起来
Node<K,V>[] oldTab = table;
//旧表长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//旧的临界值 此时threshold已经在构造函数中完成了初始化
int oldThr = threshold;
//新表长度 新表的要调整的下一个值
int newCap, newThr = 0;
if (oldCap > 0) {
//如果旧表长度大于最大容量 简而言之 太长了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
//不能增加长度
//返回原始表
return oldTab;
}
//如果旧表的长度大于16 才需要计算临界值(threshold)
//
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;
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; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果这个桶中只有一个元素
if (e.next == null)
//e.hash & 最大索引 & 只有存在两个一则为一 0 和本身
//再散列
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;
//链表中的每一个元素都要再散列??
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);
//链表的最后一个设为null
if (loTail != null) {
loTail.next = null;
//映射链表
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}