转自stackoverflow:
Q:
I read in many places saying while override equals
method in Java, should override hashCode
method too, otherwise it is "violating the contract".
But so far I haven't faced any problem if I override only equals method, but not hashCode method.
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?
A:
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
.
As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode()
.
If you have two objects which are .equals()
, but have different hash codes, you lose!
The part of the contract here which is important is: objects which are .equals()
MUST have the same .hashCode()
.
According to the doc, the default implementation of hashCode will return some integer that differ for every object
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)
However some time you want the hash code to be the same for different object that have the same meaning. For example
This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.