問題描述
如果您知道,請描述原因.我用谷歌搜索了它,但沒有找到解釋清楚的答案.
Please describe the reason if you know. I Googled it, but didn't find well explained answers.
當您的 hashCode
為負數時,是否使存儲桶的索引為正數?
Is it for making index of bucket positive when your hashCode
is negative?
推薦答案
對于HashMap
,存儲Map的條目的數組中的索引是這樣計算的(其中h
由 key 的 hashCode
計算得出):
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);
}
其中 length
是數組的長度.
Where length
is the length of the array.
這僅在 length
是 2 的冪時有效.如果 length
不是 2 的冪,則必須將此代碼更改為效率較低的 返回 h % 長度
.
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
.
這篇關于為什么HashMap的初始容量是16(2的冪)和Hashtable的初始容量是11(素數)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!