Showing posts with label equals(). Show all posts
Showing posts with label equals(). Show all posts

Wednesday, 21 March 2012

Overriding hashCode() method in Java or Why always override hashcode() if overriding equals()?

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a superclass so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of hashCode() method. We will discuss why it is necessary to override hashCode method,Why always override hashCode() if overriding equals() and how we can override them.

Default implementation of hashCode() in Object class

The signature of hashCode is:

public int hashCode()

How and Why to override the equals and hashCode methods in Java

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a superclass so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of equals() and hashCode() method. We will discuss why it is necessary to override these methods and how we can override them.

Default implementation of equals() in Object class

The default version of equals method present in the Object class has the same behavior as the == operator which in turn simply checks if two reference variables are referring the same objects.Consider x and y, two object references, then x.equals(y) comparing the memory addresses of the objects referenced by x and y (i.e. not the data of the objects).