equals() in java || Create your custom equals method

Ram Dafale
6 min readOct 23, 2019

--

I assume all readers are come here to understand how they can create their custom equals method and how it works.

If you have read my past article over equals() method then you should have learned that Object class (which is a parent of all java classes) equals method only check the reference of two objects. And we can’t rely on the check if we want to distinguish two objects if they are different/same.

So for that, we need to override the Equals() method and create own custom method in your user-define a class.

Let’s take an example of Person Class having two properties(adharId, Name).

public  class Person {
int adharId;
String name;
public Person(int adharId, String name) {
this.adharId = adharId;
this.name = name;
}
}

It all depends on us how we want to implement equals() method. Let's implement : Two objects are equals only if their adharNumber and Name are the same. So why wait let’s begin our Scenarios based learning.

  1. Scenario №1: We can implement our equals() method such that if their adharID is matching then those objects are the same.
class Person {
int adharNumber;
String name;
public Person(int adharNumber, String name) {
this.adharNumber = adharNumber;
this.name = name;
}
@Override
public boolean equals(Object object) {
Person anotherPerson= (Person) object; //downcasting from object to Person
if (this.adharNumber !=
anotherPerson.adharNumber) {
return false;
}
return true;
}

}

so now if you call equals method with the same adharNumber what will happens?

class MainClass {
public static void main(String args[]) {
Person objectOne = new Person(1, "Ram");
Person objectTwo = new Person(1, "Shyam");
boolean value = objectOne.equals(objectTwo);
System.out.println(value); //true
}
}

It will print true this time. Because we are passing the same adharNumber to both objects. If we change adharNumber of any of the objects to other than 1 then it will result in false.

2. Scenario №2 Suppose now we want to check both adharNumber and Name are the same, then two objects must be equals according to equals() method. We just need to add one more “if clause “ inside the Person class equals() method.

class Person {
int adharNumber;
String name;
public Person(int adharNumber, String name) {
this.adharNumber = adharNumber;
this.name = name;
}
@Override
public boolean equals(Object object) {
Person anotherPerson= (Person) object;
if (this.adharNumber !=
anotherPerson.adharNumber) {
return false;
}
if (this.name !=
anotherPerson.name) {
return false;
}
return true;
}

}

In this case, both adharNumber and Name, will we will be passing are the same.

class MainClass {
public static void main(String args[]) {
Person objectOne = new Person(1, "Ram");
Person objectTwo = new Person(1, "Ram");
boolean value = objectOne.equals(objectTwo);
System.out.println(value); //true
}
}

So now the answer is TRUE.

As we are dealing here with String class. We can use Equals() method implementation of String class for content comparison. This is more suitable that == operator.

So just replace that If clause(containing ==) with below one.

if (!this.name.equals(anotherPerson.name)) {
return false;
}

If you change name of 2nd object from “Ram” to “ram”. It will result in false.

Let’s dig further into “how we can make our equals() method ready to get deploy in production” Because there is a possibility that someone can pass a null object or someone can pass some other class.

So now we will cover all those scenarios.

Scenario №1 When we pass one of the objects as NULL

boolean value = objectOne.equals(null);  // passing null to equals() 
boolean value = null.equals(null);

We must handle this situation. Because If we did not then we are going to get NULLPOINTER exception. We need to make person class equals method to handle this type of situation. Cause when person.adharNumber will be executed, we will get the null pointer exception.

class MainClass {
public static void main(String args[]) {
Person objectOne = new Person(1, "Ram");
Person objectTwo = new Person(1, "Ram");
boolean value = objectOne.equals(null);
System.out.println(value); //true
}
}

So let’s write correct code for that :

@Override
public boolean equals(Object object) {
Person anotherPerson= (Person) object;
if(this == null || anotherPerson== null) // Newly added code
{
return false;
}
// above code will check if obejct passed is null or not.
if (this.adharNumber != anotherPerson.adharNumber) {
return false;
}
if (!this.name.equals(anotherPerson.name)) {
return false;
}
return true;
}

Now when we call the equals method on our two objects, our program is ready to handle the null value.

Person objectOne = new Person(1, "Ram");
Person objectTwo = new Person(1, "Shyam");
boolean value = objectOne.equals(null);
System.out.println(value); // this will result to "false".

Scenario №2 If we pass same objects to equals() method.

Person objectOne = new Person(1, "Ram");
Person objectTwo = new Person(1, "Shyam");
boolean value = objectOne.equals(objectOne);
// Here we are comparing "objectOne" with "objectOne";

Now if we pass the same object to equals method.
In equals method of person class ->>> we are checking

  1. if it null or not,
  2. We are checking adharNumber/Name are same or not and then produce a result.

Instead, we can just add one little condition like below which will check if the object coming is equal to current object or not. If they are same then don't do any further comparison.

if(this == anotherPerson )
{
return true;
}
// this line will check current object with other object and return true if their reference are same.

Scenario №3 Comparing two different class with equals method.

For example: If we add Test Class in our program which will be having same attribute as Person class.

Person objectOne = new Person(1, "Ram");
Test otherClassObject = new Test(1, "Ram");
boolean value = objectOne.equals(otherClassObject);
System.out.println(value); //guess the output

Answer: Error….. If you have guessed that then you are awesome.

Person anotherPerson= (Person) object; 
// Above code will throw CLASS_CAST_EXCEPTION. Since there is no relation between PERSON class and TEST class.

“ClassCastException” Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. So, for example, when one tries to cast an Integer to a String , String is not an subclass of Integer , so a ClassCastException will be thrown.

We can easily get read of that exception if you add below lines to our PERSON class method. In our example this.getClass() will get “Person” class and person.getClass() will get “Test” class. Both are different so result will be false.

if(this.getClass() != anotherPerson.getClass())
{
return false;
}

Now if you execute our code :

Person objectOne = new Person(1, “Ram”);
Test otherClassObject = new Test(1, “Ram”);
boolean value = objectOne.equals(otherClassObject);

value will be print “false” without any exception.

Scenario №4 What if one of the properties of object is null.

For example: Below I have passed the Name of Person as a null.

Person objectOne = new Person(1, NULL);
Person objectTwo = new Person(1, “Shyam”);

How can we handle this scenario. If we run equals method on this two object then we will get NULL POINTER EXCEPTION. Right ? give it a try.

How to fix this ?

Answer : We can fix this by adding one IF clause which checks whether the object having null or not. If it contains NULL then we can return the result as true or false based on values you passed.

if(this.name == null) // objectOne has name = null 
{
if(anotherPerson.name != null) // so this condition will be skip.
{
return false;
}
if (!this.name.equals(anotherPerson.name)) { // null!=Shyam
return false; // this will executed.
}
}

In our example this.name=null. So the program will skip the inner if clause. and then move to 2nd if clause which compares “ null” with “Shyam”. So it will return false.

If you are lazy programmer just like me then just go to Eclipse/IntelliJ IDE create your own custom class and just right-click inside your class and yeah!! your IDE will be generating same above code for you. Your IDE is capable of generating hashcode()/Equals() method on its own. give it a try!

If you want complete code. visit my Github repo :

If I am wrong somewhere please help me make it correct.

If you have any doubt you can comment below or reach out to me via ramdafale@gmail.com

Happy Coding!! Happy Reading!!

--

--