I understand that the size of the HashMap is 16 by default and we also can provide some other value to it .What if i have initialized the size as 5 with a load factor of 0.8f and then i add the fifth element to it.Does it grow to 10 or 16?Does it jumps to power of two once the threshold breach happens for a non power of 2 value?
Asked
Active
Viewed 407 times
1 Answers
5
It is always best to have a look at the 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;
...
So, the current capacity and threshold are doubled upon resize.
However, constructing a HashMap object with initial capacity that is not a power of 2 is not possible! Constructor converts the initial capacity into the power of 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);
}

davidxxx
- 125,838
- 23
- 214
- 215

Miljen Mikic
- 14,765
- 8
- 58
- 66
-
@ZerekSees Glad to help! – Miljen Mikic Apr 12 '17 at 07:27
-
1I wonder why the initial capacity must be the power of 2 ? Would it be a nearest hight number of passed capacity? – voipp May 29 '18 at 08:08
-
1@voipp Because of the easier implementation. With powers of 2, you can easily use bit shifting and other operations on bits, see e.g. this answer: https://stackoverflow.com/questions/8352378/why-does-hashmap-require-that-the-initial-capacity-be-a-power-of-two/8352426 – Miljen Mikic May 29 '18 at 08:36