問題描述
查看代碼,特別是第 393 行,看起來不同的哈希值已映射到同一個索引.我的理解是哈希碼用于確定要使用 HashMap 中的哪個桶,并且桶由具有相同哈希碼的所有條目的鏈表組成.他們為什么要檢查 e.hash == hash
?
Looking at the code specifically line 393, it looks like different hashes have been mapped to same index. I had an understanding that the hashcode is used to determine what bucket in a HashMap is to be used, and the bucket is made up of a linked list of all the entries with the same hashcode. They why have the e.hash == hash
check ?
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
推薦答案
由于 hashcode 可以是 2^32 值中的一個,hashmap 很少有這么多桶(僅表需要 16GB 內存).所以是的,您可以在地圖的相同存儲桶中擁有具有不同哈希值的對象(AFAIK 它是 hachCode % numberOfBuckets
的簡單模運算).
Since a hashcode can be one in 2^32 values, it is rare that the hashmap has so many buckets (just the table would require 16GB of memory). So yes, you can have objects with different hashes in the same buckets of the maps (AFAIK it is a simple modulus operation of hachCode % numberOfBuckets
).
注意代碼不是直接使用key.hashCode()
,而是hash(key.hashCode())
.
Note that the code does not use directly key.hashCode()
, but hash(key.hashCode())
.
這篇關于具有不同哈希值的鍵是否也映射到 HashMap 中的相同索引?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!