What is the relationship of hashCode() and equals()
Source: StackOverflow, HackerRank, Jenkov
Question: What is the relationship between hashCode()
and equals()
in Java? Why is it often recommended to override both methods?
Answer:
In short, we need to implement both method for our custom class or else It will give wrong results if our custom class is used in a data structure such as HashTable
or HashMap
which heavily depend on both methods. See the second link for how a HashTable
ultilize such data.
Here are two rules that are good to know about implementing the hashCode()
method in your own classes, if the hashtables in the Java Collections API are to work correctly:
If object1 and object2 are equal according to their equals()
method, they must also have the same hash code.
If object1 and object2 have the same hash code, they do NOT have to be equal too.