Home > Java > hashcode and equals methods

hashcode and equals methods

hashcode_1

You 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.

The identity of an object is simply that. Every object you create has its own unique identity. It doesn’t matter if two objects are of the same class, hold the same references, have the same values; if they were created separately, they have unique identities. If two different variables hold a reference to the same object instance, the objects will be identical.

your rule of thumb should be, if you override equals(), override hashcode() as well.

Collections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection, and the hashcode is used again to help locate the object in the collection.

hascode

As you can see in above diagram that every object is placed in Hash bucket depending on the hashcode they have. It is not necessary that every different object must have different hashcode. hashcode is used to narrow the search result. When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.

What will happen if I don’t override the hashcode method?
Ans : If the object does not implement hashcode() method and used as key then we will not get the object back

Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment