Wednesday, October 25, 2017

hashCode and equals, why they are needed in Java?

All object in java are inherited from Object class, this Object has two methods hashCode() and equals(Object obj). We normally do not care about why these are made and what is the significance of these methods to derived objects.

To begin with, if we have Java objects and wanted to compare those object whether they are same or not. Primitive type values can be directly compared for equality with == operator. What if we use the same operator to check equality to Java object, then we are messed up. That is because the == operator compares the reference values of the objects. That means if two objects reference to the same memory address, they are equal. To clearify this, lets take example:

int a=10;
int b=10;

a==b  //true

Integer a=new Integer(10);
Integer b=new Integer(10);

a==b //false

First example give true because we are comparing values and they are same. In case example, they are object and the references of the objects are compared, although the values are same, they are NOT equal!!!

In many problem scenario, we need some mechanism so that the objects are evaluated based on their properties. In the above example, the evaluation of a and b should give the same result because they represent same, although they are different objects. For that we need to use equals() method of Object.

public boolean equals(Object object)

So, we override and implement this method to our object so that we can evaluate objects for equality based on their contents. So, two objects are evaluated as equal if this method return true.  

public native int hashCode()

When we override equals method, we MUST override hashCode method also. Why?

[Because a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections.]

So, the rule is if equals() returns true, then their hashCode should ALWAYS be equal. But the other way might not be true. That is, if equals() returns false, it is not necessary that the two objects have different hashCodes.

How to create hash code?

How to implement equals method?

No comments:

Post a Comment