This question already has an answer here:
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?
According to the doc, the default implementation of hashCode will return some integer that differ for every object
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.
A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.
Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.
Have a look at
Hashtables
,Hashmaps
,HashSets
and so forth. They all store the hashed key as their keys. When invokingget(Object key)
the hash of the parameter is generated and lookup in the given hashes.When not overwriting
hashCode()
and the instance of the key has been changed (for example a simple string that doesn't matter at all), thehashCode()
could result in 2 different hashcodes for the same object, resulting in not finding your given key inmap.get()
.Yes, it should be overridden. If you think you need to override
equals()
, then you need to overridehashCode()
and vice versa. The general contract of hashCode() is:The problem you will have is with collections where unicity of elements is calculated according to both
.equals()
and.hashCode()
, for instance keys in aHashMap
.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.The contract is that if
obj1.equals(obj2)
thenobj1.hashCode() == obj2.hashCode()
, it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.