Equals and Hashcode in Java

Bala
4 min readMay 14, 2022
Equals and Hashcode

In this post, we are going to explore the importance of equals and hashCode methods in Java. Object class is the superclass for all other classes in Java. equals and hashCode are the methods that are part of the Object class and hence they are part of every class in java.

As a general rule,

If two objects are equal according to the implementation, their hashCode should match!

Let us approach understanding this with a scenario, Have you ever noticed what happens when an identical order is placed in Dominos app within a stipulated time by mistake (at least it happened to me twice)? Any duplicate orders will be rejected as they suspect it could be due to a mistake. Let’s take this an example and try to compare the orders using equals and hash methods

It’s recommended that both equals and hashCode methods need to be overridden to achieve better business decisions. So why its best to override these implementations? Before that, we need to understand what the base implementation does.

equals() base method

As Java is an Object-oriented programming language, except for primitives everything else is an object in Java.

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

--

--