Saturday, 13 April 2013

Understanding equals() and hashCode() methods in Java.

You must have heard that whenever you write a class of your own, you must always override equals() and hashCode()  methods.Lets us understand these methods and why it is important to override these methods.

Both these methods are defined in the Object class which is the top most class in the inheritance hierarchy. All classes implicitly extend object class and hence all class have these methods. Hence you must override these methods to suit your class requirements. Why and where they are used - we will come to it in some time.

Understanding motive behind the functions

     .equals() method is used to compare two objects. Since you only know the structure of your class you are the only one who can implement the comparison logic. For more details on this you can refer post on .equals() method. 

   .hashCode() method is used to return a unique integer value for each unique object. This unique number is used in various cases like while storing the objects in Map etc.So the motive is if two objects are same i.e if they return true on .equals() method then they must also return the same hashcode. So logic similar to .equlas() must be added to return a unique integer(hashcode) for unique objects.

Note : Reverse is not true. If two objects return the same hashcode they may or may not be same objects.

Default Implementation

public boolean equals(Object object) {
    return this == object;

public int hashCode() {
    return VMMemoryManager.getIdentityHashCode(this);


   Both your equals() and hashCode() are implementations of the programmer. Make sure to use same attributes in both these function. Whenever you override equals() method make it a point to override
hashCode() too. Key point to remember is if two objects are same they must return true from .equals() method and also they must return same hashcode from .hashCode() method.

If you are using an IDE like eclipse you can directly generate hashCode() and equals() just like generating getter and setter methods.Then add your overriding logic. Here is a snapshot of eclipse - 

No comments:

Post a Comment

t> UA-39527780-1 back to top