为什么我不能只比较两个对象的hashCode来判断它们是否相等? [英] Why can't I just compare the hashCode of two objects in order to find out if they are equal or not?

查看:242
本文介绍了为什么我不能只比较两个对象的hashCode来判断它们是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Eclipse实现的equals方法比较每个值,仅比较两个对象的hashCode是否更简单?



据我所知:


  • 因此,如果两个对象相同,则hashCode始终为同一输入生成相同的散列值,它们应该具有相同的哈希值如果对象相同的哈希值相同,那么我可以检查哈希值以确定对象是否相等。



编辑:相关的问题,为什么当equals被实现时总是实现hashCode,如果hashCode实际上不需要等于?

解决方案


hashCode总是为相同的输入生成相同的哈希值

正确。


因此,如果两个对象相同,它们应该具有相同的散列


正确。




如果相等的对象具有相同的散列值,我可以检查散列值以确定对象是否相等

非sequitur。不相等的对象也可以具有相同的哈希码。这是hashcode的目的。


相关的问题是,为什么总是在实现equals时实现hashCode,如果hashCode不是' t实际上需要等于什么?


因为需要散列,所以 HashMap,HashSet,和朋友。如果您认为您的物品永远不会被如此使用,请不要覆盖它,祝您好运。


Why do the equals methods implemented by Eclipse compare each value, wouldn't it be simpler to just compare the hashCodes of both objects?

From what I know:

  • hashCode always generates the same hash for the same input
  • So if two objects are equal, they should have the same hash
  • If objects that are equal have the same hash, I can just check the hash in order to determine of objects are equal or not

edit: Related question, why does one always implement the hashCode when equals is implemented, if the hashCode isn't actually needed for equals?

解决方案

hashCode always generates the same hash for the same input

Correct.

So if two objects are equal, they should have the same hash

Correct.

If objects that are equal have the same hash, I can just check the hash in order to determine of objects are equal or not

Non sequitur. Objects that are unequal can also have the same hashcode. That is the purpose of a hashcode.

Related question, why does one always implement the hashCode when equals is implemented, if the hashCode isn't actually needed for equals?

Because it is needed for hashing, in HashMap, HashSet, and friends. If you think your object will never be so used, don't override it, and good luck with that.

这篇关于为什么我不能只比较两个对象的hashCode来判断它们是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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