Showing posts with label Override. Show all posts
Showing posts with label Override. Show all posts

How to Override Object.equals() method in Java . Writing own equals() method to compare two objects based on values with example code

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 true
2. 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 overriding
1. 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;
}
}



Output:

Read more...

Comparing Objects by values equality by overriding equal / hashCode() method with example.

Basically , Obj1.equals(Obj2) returns true , if Obj1 and Obj2 refer to the same object that means the references of two Objects (Obj1 & Obj2 ) point to the same object which is equal to if (Obj1==Obj2) . This is the default implementation of the equal method of an Object. But we need to compare one or more values of the two Objects. This can be done by overriding the equals method (i.e boolean equals(Object obj) ) . By overriding equal method , you can write your own logic to decide wheather two objects of the same class are equal or not that is the implementor decides which values should be equal to consider two objects to be equal. In our example , in Student class, the two student objects equality is decided by the total marks.
In the following program, Student class is defined with fields of name , Mark1 , Mark2, Mark3 and One constructor to assign values and public methods to access fields. We can create one or more student objects from Student class. Our objective is to check two student objects are equal or not based on the total value of 3 marks .So we have overrided the equal method by writing the logic to compare total marks of two objects of same class. The hashCode method has to be redefined as we are redefining the equals method . The concept is the Equal objects must have equal hash codes.

class Student
{
private String name;
private int mark1;
private int mark2;
private int mark3;
public Student(String name, int m1, int m2, int m3)
{
this.name=name;
this.mark1=m1;
this.mark2=m2;
this.mark3=m3;
}
public String getName() { return this.name; }
public int getMark1() {return this.mark1;}
public int getMark2() { return this.mark2; }
public int getMark3() { return this.mark3; }

public void printValues()
{
System.out.println("name : " + this.name);
System.out.println("M1 : " + this.mark1);
System.out.println("M2 : " + this.mark2);
System.out.println("M3 : " + this.mark3);
}
public boolean equals(Object obj)
{
boolean eq=false;
//if both object's reference is equal means , objects are equal
if(this == obj) return true;
if (obj instanceof Student)
{
Student student = (Student) obj;
int tot1=student.getMark1() + student.getMark2() + student.getMark3();
int tot2=this.getMark1() + this.getMark2() + this.getMark3();
if (tot1==tot2) eq=true;
//the following line checks name also to decide Object's equality
// if ((tot1==tot2) &&( student.getName().equals(this.getName())) ) eq=true;
return eq;
}
else
{
return false;
}
}
//hashCode() is overrided.
public int hashCode()
{
int hash = 19;
String tot1=Integer.toString(mark1+mark2+mark3);
hash = 37 * hash + tot1.hashCode();
//hashCode() of 'name' field is also considered in the below line. If equal method use 'name' field means , hashCode() also has to use.
//hash = 37 * hash + name.hashCode() +tot1.hashCode();
return hash;
}
}

//Class to create Students objects and compare two student objects for equality using overrided equal method

class OverrideEqual
{
public static void main(String args[])
{
Student stu1 = new Student("ABC", 50, 30, 21);
Student stu2 = new Student("XYZ", 50, 30, 21);
stu1.printValues();
System.out.println("");
stu2.printValues();
if ( stu1.equals(stu1) ) System.out.println("Both object references point to the same object"); else System.out.println("Both are different objects");
if ( stu1.equals(stu2 ) ) System.out.println("Both student are equal"); else System.out.println("Both students are not equal");
if ( stu2.equals(stu1 ) ) System.out.println("Two students are equal"); else System.out.println("Two student are not equal");
if (stu1.hashCode()==stu2.hashCode()) System.out.println("Both Student Object Hashcode are equal"); else System.out.println("Both Student Object Hashcode are not equal");

}
}


//Output :

Read more...

 
Copyright 2011 Java Online