Why do we need to override the equals and hashcode methods in java


When we need to use our object in the hashing based collections, we must override both equals() and hashCode() methods.

We must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.   --from Effective Java, by Joshua Bloch

When we need to override equals() method:

The default implementation of Object.equals() method will be considered if two objects have same memory(referential) address and it will return true if we are comparing an object with itself. We need to override equals() method If we want logical equality.

When we need to override hashCode() method:

While inserting an object into a hash-based collection we use key. The hash code of this key is calculated, and used to determine where to store the object internally. When we need to lookup an object in this collection again we use key. The hash code of this key is calculated and used to determine where to search for the object.

The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The collection (hash-based) then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

So, as we can see, a combination of the hashCode() and equals() methods are used when storing and when looking up objects in a hash-based collections. 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.

  • If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.
  • It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

img logo

No comments :

Post a Comment