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

核能气质少年 提交于 2020-08-19 04:20:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27251480/why-is-the-initial-capacity-in-hashmap-16-power-of-two-and-the-initial-capacit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!