Understanding equals and hashCode in Java 
Tags: java, interview, tutorial, webdev
Published: 2021-01-31 23:39:39


*This post was originally published here at https://balasr.com/blog/2n857rotH9da7mBF5ZWO2V*

This is going to be one of the series of posts related to Interview topics that I would be writing. In this post, we are going to explore the importance of equals and hashCode methods in Java.

equals() and hashCode() are two methods that are part of every class 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

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?

Any duplicate orders will be rejected as they suspect it could be due to a mistake.

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 does the base implementation does.

<center>**equals() base method**</center>
___

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);
}
```

The base implementation compares and identifies whether the current object and the passed object are one and the same i.e., they share the same memory location as in the below diagram. Both the objects have the same reference in the heap memory

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e5r3ggwm5kdhi8d8tyjq.png)

<center>**hashCode() base method**</center>
___
This method returns the hash value of the given object as an integer value. Within the application lifetime, it's expected that the hashCode value of an object remains the same regardless of the however number of times it got invoked.

Hence if 2 objects are considered equal according to the default equals method then their hashCode value will always be the same.

<center>**Overridding equals() method**</center>
___

Coming back to our scenario, according to our requirement, any 2 orders are equals if their attributes (ordering user, order items, quantity, and delivery address) are the same. So let's override the equals method to reflect the same
equals method alone overridden as below

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0muw1qo6u3rmp0t9bdem.png)

Result when the equal method is overridden

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/00phn0fgo0kue5nrpvqh.png)

<center>**Impact if hashCode() method is not overriden**</center>
___
The impact would be visible if the orders are stored in hash-based collections. For instance, consider the below example where orders are maintained in HashSet and we try to perform whether the newly received order is already present with us. This would be a problem as we have not overridden the hashCode method yet

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2941jviacdhgku52wxq7.png)

As you can see in the above image, 2 orders even as per our requirements are equal, it's being considered as not equal.

<center>**Overriding hashCode() method and equal()**</center>
___

Let's override the hashCode method to include a combination of our attributes (this is one of the ways) for comparison

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pr643zr69p0ezp9lhhnj.png)

Now let us compare orders with both equal and hashCode overridden as per our requirement

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tllgs7zb4q5sutovfd4h.png)

As we can see, overriding equals and hashCode method results in exactly what we are looking for in case of any type of collections the orders are being stored

So always respect the contract, it's binary either both methods (equals and hashcode) should be overridden or none of both methods.

This will be one among the series of posts that I would be writing which are essential for interviews. So if you are interested in this thread and found it useful, please follow me at [my website](https://balasr.com) or [dev](https://dev.to/balasr21)