问题
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