据我所知,默认情况下HashMap的大小为16,我们也可以为它提供一些其他值。如果我将大小初始化为5,加载因子为0.8f然后我将第五个元素添加到它是否会增长到10或16?如果非幂2值发生阈值突破,它会跳到2的幂吗?
答案 0 :(得分:5)
最好看看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);
}