use*_*215 4 java hashtable hashmap hashcode
我知道 hashmap 实际上使用哈希码来存储和检索哈希表中的对象,但我怀疑它使用的是哪个哈希码。map 实际上包含键的哈希码和值的哈希码。让我们这样考虑
Map<String,String> student=new HashMap();
student.put("name", "foo");
System.out.println("name".hashCode());
System.out.println("foo".hashCode());
Run Code Online (Sandbox Code Playgroud)
在这里,name(key) 的 hashcode 是 3373707,foo(value) 的 hashcode 是 101574
我怀疑它应该使用哪一个来存储和检索对象
从 中的以下代码可以看出HashMap,它使用自己的哈希函数:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
Run Code Online (Sandbox Code Playgroud)
它使用对象的hashCode, 但xors 它并在算术上将其向右移动 16 次。
要具体回答您的问题,它使用hashCode键的 ,而不是值。
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |