Relationship between hashCode and equals method in Java
Yes, it should be overridden. If you think you need to override equals()
, then you need to override hashCode()
and vice versa. The general contract of hashCode() is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
The contract is that if obj1.equals(obj2)
then obj1.hashCode() == obj2.hashCode()
, it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.
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()
.
This is all documented in the javadoc for Object
. And Joshua Bloch says you must do it in Effective Java. Enough said.
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
Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode
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.