使用不同散列的密钥也可以映射到HashMap中的相同索引? [英] Do keys with different hashes also get mapped to the same index in HashMap?

查看:118
本文介绍了使用不同散列的密钥也可以映射到HashMap中的相同索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

专门查看第393行的代码,看起来不同的哈希已经映射到相同的索引。我了解哈希码用于确定HashMap中要使用的存储桶,并且存储桶由具有相同哈希码的所有条目的链接列表组成。他们为什么要检查 e.hash == hash

  

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);
返回oldValue;
}
}
modCount ++;
addEntry(hash,key,value,i);
返回null;
}


解决方案

散列码可以是2 ^ 32个值中的一个,散列表有很多存储桶(仅表格需要16GB内存)很少见。所以是的,你可以在地图的同一个桶中拥有不同哈希的对象(AFAIK它是一个简单的模数运算 hach​​Code%numberOfBuckets )。



请注意,代码不直接使用 key.hashCode(),而是 hash(key.hashCode() )


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;
    }

解决方案

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).

Note that the code does not use directly key.hashCode(), but hash(key.hashCode()).

这篇关于使用不同散列的密钥也可以映射到HashMap中的相同索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆