Java中hashCode和equals方法的关系

问题描述:

我在很多地方都看到在Java中重写equals方法时,也应该重写hashCode方法,否则就是违反合同".

I read in many places saying while override equals method in Java, should override hashCode method too, otherwise it is "violating the contract".

但到目前为止,如果我只覆盖 equals 方法而不是 hashCode 方法,我还没有遇到任何问题.

But so far I haven't faced any problem if I override only equals method, but not hashCode method.

合同是什么?为什么我在违反合同时没有遇到任何问题?在什么情况下,如果我没有覆盖 hashCode 方法,我会遇到问题吗?

What is the contract? And why am I not facing any problem when I am violating the contract? In which case will I face a problem if I haven't overridden the hashCode method?

您将遇到的问题是根据 .equals() 计算元素唯一性的集合.hashCode(),例如HashMap 中的键.

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

顾名思义,它依赖于哈希表,而哈希桶是对象的.hashCode()的函数.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

如果你有两个 .equals() 对象,但是哈希码不同,你就输了!

If you have two objects which are .equals(), but have different hash codes, you lose!

这里合同中重要的部分是:.equals() 的对象必须具有相同的 .hashCode().

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

这一切都记录在 对象代码>.Joshua Bloch 说你必须在 有效的 Java.说的够多了.

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.