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

Please describe the reason if you know. I searched for it but did not find well-explained answers.

Is this to make the bucket index positive when your hashCode negative?

+6
source share
1 answer

For a HashMap index in the array that stores the Map entries is calculated this way (where h calculated from the hashCode 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 not power 2, you will have to change this code to a less efficient return h % length .

+7
source

Source: https://habr.com/ru/post/978995/


All Articles