Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the initial capacity in HashMap 16 (power of two) and the initial capacity of Hashtable 11(prime number)?

Please describe the reason if you know. I Googled it, but didn't find well explained answers.

Is it for making index of bucket positive when your hashCode is negative?

like image 455
niiraj874u Avatar asked Dec 02 '14 14:12

niiraj874u


1 Answers

For HashMap, the index in the array that stores the entries of the Map is calculated this way (where h is calculated from the hashCode of the key):

static int indexFor(int h, int length) {
    return h & (length-1);
}

Where length is the length of the array.

This only works when length is a power of 2. If length wasn't power of 2, you would have to change this code to the less efficient return h % length.

like image 56
Eran Avatar answered Oct 14 '22 17:10

Eran