Do keys with different hashes also get mapped to the same index in HashMap?(具有不同哈希值的键是否也映射到 HashMap 中的相同索引?)
问题描述
查看代码,特别是第 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 中的相同索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有不同哈希值的键是否也映射到 HashMap 中的相


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01