Comparing the HashMap and Hashtable source code in JDK 1.6, I saw the below code inside HashMap:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
However, in Hashtable, I saw this:
table = new Entry[initialCapacity];
public Hashtable() {
this(11, 0.75f);
}
So my question is:
Why does HashMap require a power of 2 as the initial capacity, while Hashtable chooses 11 as the default initial capacity?
I assume this has nothing to do with the thing that Hashtable is thread-safe and does not allow null key or values.
The following article addresses this question in some detail: HashMap requires a better hashCode() – JDK 1.4 Part II.
According to that article, the main reason to move to power-of-two sizes was that bit masking is faster than integer division. This is not without adverse consequences, which are explained by one of the original authors: