Why can't I just compare the hashCode of two objects in order to find out if they are equal or not?

雨燕双飞 提交于 2019-12-25 02:54:00

问题


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?


回答1:


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.




回答2:


To complement @EJP's answer, here is a perfectly valid, although useless, implementation of .hashCode():

@Override
public int hashCode()
{
    return 42; // The Answer
}



回答3:


Putting this in very simple terms: while every squirrel is an animal, not every animal is a squirrel. The hashCode is usually used for quick lookup - it should be efficient and it should distribute data uniformly across a lookup table - see here. But a hash function can generate collisions, which is why it shouldn't be used as a means of verifying object equality.

It's all very much dependent on the implementation of hashCode - as you can also see in fge's answer.

As to why it usually needs to be reimplemented when you override equals: they are both used when storing and retrieving objects from collections (for example a HashMap). The hashCode determines the place in the map where the object will be inserted, while equals is used to identify the object inside a collision bucket.



来源:https://stackoverflow.com/questions/29714448/why-cant-i-just-compare-the-hashcode-of-two-objects-in-order-to-find-out-if-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!