Interview question: Why is it important to override hashCode and equals in Java?
The methods hashCode and equals are two methods defined in the Object class, from which all Java objects are extended from.
It is necessary to override hashCode and equals in any class that is going to be used as a key in a HashMap, HashSet, or Hashtable. Effectively the hashCode method is used to identify a bucket for the key within the hash.
A very important rule is whenever hashCode is overridden, equals must be overridden as well:
If you fail to override the hashCode method, two identical objects placed into a hash data structure may result in the same entry getting placed into the hash data structure twice.
If you fail to override the equals method, it may be impossible to retrieve an object that was placed into a hash data structure because calling remove(value) or contains(value) will not be able to locate the value.