HashMap不调用Object.equals? [英] HashMap Not Calling Object.equals?

查看:203
本文介绍了HashMap不调用Object.equals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个类,它覆盖Object类中的equals(Object)方法,使用对象的实例值将类类型的对象与类类型的其他对象进行比较。



当我将一个HashMap中的对象实例作为关键字,然后用一个新的但相同的对象作为关键字在地图上调用get(Object)时,它将返回null。



我试过给equals方法传递一个新的,相同的对象,它返回true,所以问题不在于我的比较代码。



从调试中得到的结果,我的对象中的equals(Object)方法永远不会被调用。

但是如果你在一个HashMap中使用一个String键,然后传递一个具有相同字符的新实例以获取(Object),它将成功返回值。



为什么会发生这种情况?我需要做什么才能使用基于MY等号方法的HashMap测试键?

解决方案

您还需要覆盖 是Object.hashCode() 。看看这个链接,因为它指定了 hashcode() equals()有一个合约来确保正确在 HashTable 中, HashMap 的和 HashSet 's。


$ b $ <$>在 HashMap 中,值存储在存储区中,存储区的哈希码键。一旦找到合适的存储桶,就会将equals方法应用于存储桶的每个成员,直到确定相等。因此,确保散列算法散列好非常重要。


I wrote a class that overrides the equals(Object) method in class Object to compare objects of the class type to other objects of a class type using the object's instance values.

When I put an instance of the object in a HashMap as the key, and then call get(Object) on the map with a new but identical object as the key, it returns null.

I've tried passing a new, identical object to the equals method and it returns true, so the problem isn't my comparison code.

From what I've gathered through debugging, the equals(Object) method in my object is never called.

But if you use a String key in a HashMap and then pass a new instance with identical characters to get(Object), it returns the value successfully.

Why is this happening? What do I have to do to have HashMap test keys based on MY equals method?

解决方案

You need to also override Object.hashcode(). Take a look at the link, as it specifies that hashcode() and equals() have a contract to ensure proper functionality in HashTable's, HashMap's, and HashSet's.

In a HashMap, values are stored in buckets, which are reached by the hashcode of the key. Once the proper bucket is found, the equals method is then applied to each member of the bucket until equality is determined. Because of this, it is important to make sure that your hash algorithm 'hashes well'.

这篇关于HashMap不调用Object.equals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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