HashMap调整其表格大小
问题描述:
我知道默认情况下HashMap的大小是16,我们也可以提供一些其他值。如果我已经初始化大小为5,负载因子为0.8f然后我添加是它的第五个元素。它是否增长到10或16?一旦阈值违约发生2值的非幂次,它会跳到2的幂次方吗?HashMap调整其表格大小
答
它始终是最好有一个看看source code:
final Node<K,V>[] [More ...] 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;
...
// The capacity of the inner data structure is doubled
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
...
因此,电流容量和阈值调整大小时翻了一番。
但是,构建一个初始容量不是2的幂的HashMap对象是不可能的!构造函数将初始容量转换为2的幂:
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY: n + 1;
}
public [More ...] HashMap(int initialCapacity, float loadFactor) {
...
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
谢谢,这是实际的问题。 – ZerekSees
@ZerekSees很高兴帮助! –