源码分析
程序员文章站
2022-07-15 20:25:49
...
/**
* 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.
* 初始化或加倍表大小。如果为空,则根据字段threshold中的initialcapacity目标进行分配。否则,因为 * 我们使用的是二次幂展开,所以每个bin中的元素要么保持在相同的下标,要么在新表中以二次幂偏移量移动。
* @return the table
*/
final Node<K, V>[] resize() {
Node<K, V>[] oldTab = table;//原table
int oldCap = (oldTab == null) ? 0 : oldTab.length;//原容量
int oldThr = threshold;//原阈值
int newCap, newThr = 0;//新容量、新阈值
if (oldCap > 0) {//原容量大于0
if (oldCap >= MAXIMUM_CAPACITY) {//原容量大于等于最大容量
threshold = Integer.MAX_VALUE;//Integer.MAX_VALUE作为阈值
return oldTab;
} else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)//原容量的2倍小于最大容量,且原容量大于默认初始化容量
newThr = oldThr << 1; //新阈值为原阈值的2倍(即原容量扩容,阈值也跟着扩容)
} else if (oldThr > 0) // 原阈值大于0
newCap = oldThr;//将原阈值作为新容量
else { // 初始化容量为0,使用默认容量和默认阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {//新阈值为0
float ft = (float) newCap * loadFactor;//新容量乘以负载因子获得临时变量ft
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float) MAXIMUM_CAPACITY ? (int) ft : Integer.MAX_VALUE);//新容量小于最大容量并且临时变量ft也小于最大容量,将ft作为新阈值,否则将Integer.MAX_VALUE作为新阈值
}
threshold = newThr;//新阈值作为阈值
@SuppressWarnings({ "rawtypes", "unchecked" })
Node<K, V>[] newTab = (Node<K, V>[]) new Node[newCap];//根据新容量创建新数组
table = newTab;//新数组作为HashMap的数组
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;
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;
}
}http://yezishuju.com/
}
}
}
return newTab;
}
上一篇: 免Oracle客户端安装的开发部署方法
下一篇: 实现一个不能被继承的类