This tutorial covers how to write own version of equals() method and importance of the method. Before going to this , let us see litle bit about Object class which has equals() and hashcode() method. Object class is the superclass of all Java classes. Every classes in java are inherited from this class by default that means all methods of the Object class are inherited automatically. So by default , the classes that we create will have the methods equals() , hashcode() , toString(), etc ...
This tutorial covers the default implementation of equals method and when and why we need to override equals method for our class?
In default implementation , two objects are equal only if they refer to the exact same object (i.e. reference / memory address equality) . The following code represents the default equals method
public boolean equals(Object obj) { return (this == obj); } When to override Object.equals() method? Please go through the following code and the output.
class equalTest
{
public static void main(String arg[])
{
Employee emp1=new Employee(1561, "John", "Smith");
Employee emp2=new Employee(1561, "John" ,"Smith");
Employee emp3=emp1;
if (emp1.equals(emp2)) System.out.println("Both Employees(emp1 , emp2) are equal");
else System.out.println("Both Employees(emp1 , emp2) are not equal");
if (emp3.equals(emp1)) System.out.println("Both Employees(emp1 , emp3) are equal");
else System.out.println("Both Employees(emp1 , emp3) are not equal");
String name1="John Smith";
String name2="John Smith";
if (name1.equals(name2)) System.out.println("Both Names(name1 , name2) are equal");
else System.out.println("Both Names(name1 , name2) are not equal");
}
}
class Employee
{
int empCode;
private String firstName;
private String surname;
public Employee(int empCode, String firstName, String surname)
{
this.empCode=empCode;
this.firstName=firstName;
this.surname=surname;
}
}
Output :D:\as2\JF4>java equalTest
Both Employees(emp1 , emp2) are not equal
Both Employees(emp1 , emp3) are equal
Both Names(name1 , name2) are equal
Before overriding , it is very important to keep in mind the distinction between equality and identity . In the above code , emp1 and emp2 has identical data i.e. employee code , first name and surname are equal for both objects . But the output is
Both Employees(emp1 , emp2) are not equal . Because, by default the equals method of object checks whether the two reference variables(emp1 and emp2 ) refer to the same object . In the above code , both are different objects that is not identical . But emp1 and emp3 are identical . So the output is
Both Employees(emp1 , emp3) are equal .
emp1 and emp2 objects are logically equal but not identical . In this situation , we have to override equals method sothat the it can also check the logical equality . But name1 and name2 are two different string objects . But the output is
Both Names(name1 , name2) are equal . Because String class overrides the equals method to compare two string objects for equality based on the values and returns true if they hold the same characters in the same sequence.
Date class defines the equals method as follows . This is the value-based approach to equality (logical equality) . Both Date objects are equal if the
getTime() method returns the same long value (milliseconds) for both
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
So when is it appropriate to override Object.equals? When a class requires logical equality ( i.e. two objects are equal if they have identical data)) that differs from object identity, and a superclass has not already overridden equals method to implement the desired behavior . This is generally applicable for value classes such as String , Integer and Date, etc . When we compare two objects using the equals method , we may expect to find out whether they are logically equivalent, not whether they refer to the same object. In this situation , we need to override equals method.
typesafe enum value class that does not require the equals method to be overridden . Because typesafe enum classes guarantee that at most one object exists with each value, Object’s equals method is equivalent to a logical equals method for such classes. When you override the equals method of java.lang.Object , you must adhere to its general contract which is given below
Let us say a, b and c are references of any objects . The equals method is
1. reflexive: a.equals(a) must return true i.e. any object must be equal to itself
2. symmetric: a.equals(b) must be true if b.equals(a) is true. i.e. if first object is equal to a second and the second object is equal to first
3. transitive: if a.equals(b) returns true and b.equals(c) returns true, then a.equals(c) must return true . i.e. if first object is equal to a second and the second object is equal to a third, then the first object must be equal to the third.
4. consistent: multiple invocations of a.equals(b) should return the same result (i.e. either always true or always false) unless any of the object's information is modified
5. Non-nullity : x.equals(null) must return false where x is non-null reference. i.e. all objects must be unequal to null. Allowing null value should not throw NullPointerException .
Note : It is better to check null i.e. if (o == null) return false;. But ,this test is not necessary as we include another test
instanceof operator to check that its argument is of the correct type i.e. if (!(o instanceof MyType)) return false; This take takes care of the null check also . instanceof operator is specified to return false if its first operand is null . null objects will always fail instanceof.
equals() method will have the following condtions and statements in the following order and applicable for the above class Employee
public boolean equals(Object other) {
1. check other object refers the same object . use == operator . If so, return true
-
if (other==this ) return true2. check that its argument is of the correct type before type casting
-
if (!(other instanceof Employee)) return false // takes care of null check also .
3. type cast the argument to an appropriate type to access its fields
-
Employee emp = (Employee) other 4. check to see if the fields (relevent to logical equality) of the argument matches the corresponding fields of this object . If all checks succeed, return true. For primitive fields (except float or double) , use the == operator for comparisons; for object reference fields, invoke the equals method recursively .To avoid NullPointerException, when the fields contain null values , please include null check as given below.
-
return empCode == emp.empCode && (firstName == emp.firstName || (firstName != null && firstName.equals(emp.firstName) ))&& (surname == emp.surname || (surname != null && surname.equals (emp.surname))) }
Note : instanceof is most suitable for immutable class or final class which can not be extended . As instanceof returns true for subclass also , we can use getCalss() method for type check as given below
if((other == null) || (other.getClass() != this.getClass())) return false . null check also required.
Aoid common mistakes when overriding1. You must override hashCode in every class that overrides equals. If not , it will result in a violation of the general contract for Object.hashCode, which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable. For overriding hashCode() method , please gothrough my earlier tutorial
Why and When to override Object.hashCode() method? 2. Don’t use any other type other than Object as argument in the equals method declaration .
Wrong : public boolean equals(Employee o) {... } - this method does not override Object.equals() , but overloads it instead. Object.equals accepts only the argument of type Object ,
Correct : public boolean equals(Object o) {... }
The above Employee class with equals() and hashCode() method is given below. The equals() method of Object class is overrided in the code to compare objects based on values.
class equalOverride
{
public static void main(String arg[])
{
Employee emp1=new Employee(1561, "John", "Smith");
Employee emp2=new Employee(1561, "John" ,"Smith");
Employee emp3=emp1;
if (emp1.equals(emp2)) System.out.println("Both Employees(emp1 , emp2) are equal");
else System.out.println("Both Employees(emp1 , emp2) are not equal");
if (emp3.equals(emp1)) System.out.println("Both Employees(emp1 , emp3) are equal");
else System.out.println("Both Employees(emp1 , emp3) are not equal");
String name1="John Paul";
String name2="John Paul";
if (name1.equals(name2)) System.out.println("Both Names(name1 , name2) are equal");
else System.out.println("Both Names(name1 , name2) are not equal");
}
}
class Employee
{
int empCode;
private String firstName;
private String surname;
public Employee(int empCode, String firstName, String surname)
{
this.empCode=empCode;
this.firstName=firstName;
this.surname=surname;
}
public boolean equals(Object other) {
if (other==this ) return true;
if (!(other instanceof Employee)) return false;
Employee emp = (Employee) other;
return empCode == emp.empCode && (firstName == emp.firstName || (firstName != null && firstName.equals(emp.firstName) ))&& (surname == emp.surname || (surname != null && surname.equals (emp.surname))) ;
}
public int hashCode() {
int hash = 17;
hash = hash * 19 + empCode;
hash = hash * 31 + firstName.hashCode();
hash = hash * 13 + (surname == null ? 0 : surname.hashCode());
return hash;
}
}