The hashCode()
method is used to generate a unique numerical value (hash code) for each object, which is used to quickly identify the object in a collection. The equals()
method is used to determine if two objects are equal.
The general contract of hashCode()
method is that it should return the same value for two objects that are equal according to the equals()
method. Therefore, if you override the equals()
method, it is important to also override the hashCode()
method to ensure that two equal objects have the same hash code.
If hashCode()
and equals()
methods are not overridden correctly, it can cause issues when trying to access objects from collections like HashMap
, HashSet
or Hashtable
.
For example, if two objects are considered equal, but have different hashcodes, these two objects will be stored in different locations in the collection, which will lead to unexpected results when trying to retrieve them.
In short, when two objects are equal, their hashcodes must be equal too, hence it's important to override hashCode()
whenever equals()
is overridden in order to maintain consistency and avoid unexpected results.