Java中hashCode与equals方法的关系 [英] Relationship between hashCode and equals method in Java
问题描述
我在许多地方读到,虽然在Java中覆盖等于
方法,但也应该覆盖 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()
计算元素的单一性的集合,例如键入a 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
.
顾名思义,它依赖于哈希表,哈希桶是一个函数object的 .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()
.
这些都记录在中对象
的javadoc。 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.
这篇关于Java中hashCode与equals方法的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!