1.

When Do We Need To Override Hashcode() And Equals() Methods?

Answer»

The default implementation of equals() method in the Object class is a simple reference EQUALITY check.

public boolean equals(Object obj){
return (this == obj);
}

The default implementation of hashCode() in the Object class just returns INTEGER VALUE of the memory address of the object.

It becomes very important to override these two methods in case we are using a custom object as KEY in a hash based collection. 

In that case we can't rely on the default implementation provided by the Object class and need to provide custom implementation of hashCode() and equals() method.

If two objects Obj1 and Obj2 are equal according to their equals() method then they must have the same hash code too. Though the vice-versa is not true that is if two objects have the same hash code then they do not have to be equal too.

The default implementation of equals() method in the Object class is a simple reference equality check.

public boolean equals(Object obj){
return (this == obj);
}

The default implementation of hashCode() in the Object class just returns integer value of the memory address of the object.

It becomes very important to override these two methods in case we are using a custom object as key in a hash based collection. 

In that case we can't rely on the default implementation provided by the Object class and need to provide custom implementation of hashCode() and equals() method.

If two objects Obj1 and Obj2 are equal according to their equals() method then they must have the same hash code too. Though the vice-versa is not true that is if two objects have the same hash code then they do not have to be equal too.



Discussion

No Comment Found