equals() method in java

In this article, we will discuss the most important topic, which is the equals() method in Java.
Everyone knows the equals() method in java is used to compare the objects. But how we can use it? How to override the equals() method in java in user-defined classes.
Here is the table content of the article will we will cover this topic.

1. What is the equals() method?
2. Why OR When we should Override the equals() method?
3. Best practices for Overriding equals() method?

What is the equals() method?

The equals() method is defined in Object class which is the super most class in Java. This method is used to compare two objects and it returns the boolean value based on the comparison. Let’s have a look at code.

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

As you can see in the above code, it compares the given object obj to “this” object. Here “this” is the object on which the method is called.

As you already know every class in java is the child of Object class. It means each class inheriting the equals() method from Object class. You can override the equals() method as per your functionality. Suppose you want to compare the objects own equality condition. Then it is recommended to override equals(Object obj) method.

NOTE: It is always recommended if you are overriding the equals() then you must override the hashCode() method. We’ll discuss it in detail.

Let’s take the example from the String class.
In the String class, equals() method is overridden and provided the equality condition accordingly.

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String aString = (String)anObject;
            if (coder() == aString.coder()) {
                return isLatin1() ? StringLatin1.equals(value, aString.value)
                                  : StringUTF16.equals(value, aString.value);
            }
        }
        return false;
    }

As you can see in the above code the String class overridden the method and comparing two strings. It compares the two given strings based on the content of the string. It returns the boolean value. If both strings are not the same then it returns false otherwise, it returns true.

Why OR When we should Override the equals() method?

The default implementation of the equals() method compares only the references of objects. But sometimes default implementation is not useful, and we want to compare the objects as per our requirements. In these types of situations, it is better to override the equals() method.

Let’s discuss it with example. We will create a user-defined class and let’s see what will be the result of comparison when we will override the equals() method in java or not?
Let’s take an example of the default implementation in java equals() method.

public class Employee 
{
	int empId;
	String name;
	
	public static void main(String[] args) 
	{
		Employee emp1 = new Employee();
		emp1.name = "Ravi";
		emp1.empId = 1;
		
		Employee emp2 = new Employee();
		emp2.name = "Ram";
		emp2.empId = 2;
		
		System.out.println("Is both employee have same id:");
		System.out.println(emp1.equals(emp2));
		
		Employee emp3 = new Employee();
		emp3.name = "Ram";
		emp3.empId = 2;
		
		System.out.println(emp2.equals(emp3));
          }
}

Output: Is both employee have same id:
false
false

Reason: You must saw emp2 and emp3 have the same name and id. But equals() method saying these do not equal because when we compare emp2 and emp3, it is checked whether both emp2 and emp3 refer to the same object or not. The compiler made a call to equals() method of Object class and it compares the references of the object.

equals() method in java

The emp2 and emp3 refer to two different objects, hence the value (emp2 == emp3) is false.
If we create another reference say emp4 like following:

Employee emp4 = emp3;
then (emp3 == emp4) will give true.

So, how do we check for equality of values inside the objects?
We can achieve this task by overriding the equals() method of Object class. We can override the equals() method in our class to check whether two objects have the same data or not.

public class Employee 
{
	int empId;
	String name;
	
	public static void main(String[] args) 
	{
		Employee emp1 = new Employee();
		emp1.name = "Ravi";
		emp1.empId = 1;
		
		Employee emp2 = new Employee();
		emp2.name = "Ram";
		emp2.empId = 2;
		
		System.out.println("Is both employee have same id:");
		System.out.println(emp1.equals(emp2));
		
		Employee emp3 = new Employee();
		emp3.name = "Ram";
		emp3.empId = 2;
		
		System.out.println(emp2.equals(emp3));
		
	}
	
	@Override
	public boolean equals(Object obj)
	{
		return ((Employee)obj).empId == this.empId;	
		}
}

Output: Is both employee have same id:false
true

NOTE: Whenever we override the equals() method, it is recommended to also override the hashCode() method. If you are not overriding the hashCode() method, it can give different hash values in case of collections. We will discuss this in a separate post.

Best practices for Overriding equals() method

Let’s discuss the best approach to overriding equals() method in Java.

1.  You must place the null check in the equals() method. If the given object is null, then return false.

public boolean equals(Object obj)
{
	if(obj == null)
		return false; 
	return ((Employee)obj).empId == this.empId;	
}

2. Before making a comparison further, you must check whether both objects are belonging to the same class or not. You can check this by use of getClass() method.
You can use the instanceOf operator also but instanceOf check returns true for subclass also, so it does not strictly equal comparison.

public boolean equals(Object obj)
{
	if(obj == null || this.getClass() != obj.getClass())
		return false; 
	return ((Employee)obj).empId == this.empId;	
}

3. You should try to compare numeric attribute because comparing numeric attribute is fast. But in some case numeric value is not available then you can compare those attributes which take less time to compare. If the first attribute comparison does not match, then return false. You should not try to match the rest of the attributes.

4. It would be better if you are using @Override annotation whenever overriding the method.
Reason:  Let’s say programmer wants to overload the equals() method of Object class.

public boolean equals(Object obj);

 but  unintentionally he/she overloads equals method by writing:

 public boolean equals(Employee obj) 

Instead of using Object as an argument they use the class name(Employee). If you use @Override annotation, then the compiler takes care of these things. If the equals() method is not overridden or programmer made some typo mistake then the compiler will show a compilation error.

The method equals(Employee) of type Employee must override or implement a supertype method.

@Override
public boolean equals(Object obj)
{
	if(obj == null || this.getClass() != obj.getClass())
		return false; 
	return ((Employee)obj).empId == this.empId;	
}

2 thoughts on “equals() method in java”

Leave a Comment