Override equals method in java

Equals and hashCode in Java are two fundamental methods that are declared in Object class and part of the core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object. equals and hashCode have used extensively in Java core library like they are used while inserting and retrieving Object in HashMap

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable is pointing to the same memory location i.e. essentially they are the same object.

Steps to Override equals method in Java

Here is one approach to override the equals method in Java.

1). this check

If condition success then returns true.

public boolean equals(Object object) {
if(this==object) {
return true;}
}
 

2). null check

If condition success then return false.

if((object == null)  
{ return false; 
}

3). instance of check

If instanceof return false than return false.

The instead of instanceof we can use getClass() method for type identification as, instanceof check returns true for subclass also, so its not strictly equals comparison. But instanceof good option if your class is immutable and no one is going to subclass it.

public boolean equals(Object object) { 
  if(o instanceof Student){
Student s2 =(Student)object;
//do the operations } if((object == null) || (object.getClass() != this.getClass())) { return false; } }

4). Typecast the object

Then instanceof check must be prior to casting object.

public boolean equals(Object object) {
  
if(object instanceof Student){
Student s2 =(Student)object;
  }
 } 
 

5). Compare individual attributes

Start comparing from the numeric attribute.

The comparison for numeric attributes is fast. We have to use a short circuit operator for combining checks. If first field does not match, don't try to match rest of attribute and return false.

 Its necessary to null check on individual attribute before calling equals() method on them recursively to prevent NullPointerException during equals check.

 
public boolean equals(Object object) {
if(o instanceof Student){
Student s2 =(Student)o;
if (age==s2.age&& name.equals(s2.name) ) {
return true;}

else
{
return false;}
}
}


Here we have code example for overriding equals method in Java

  
public class Student {
String name;
int age;

Student(String name,int age) {
this.name=name;
this.age=age;
} 

public boolean equals(Object o) {
if(this==o) {
return true;}

if(o instanceof Student){
Student s2 =(Student)o;
if(name.equals(s2.name) && age==s2.age) {
return true;}

else
{
return false;}
} return false;
}

public static void main(String[] args)
{
Student s1 =new Student("Anna",12);
Student s2 =new Student("Anna",12);
Integer i = new Integer(13);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(i));
}
}

Output:
true
false


Note: in all wrapper classes, in string class, in all collection classes .equals() method is overridden for content comparison in our classes also it is highly recommended to override .equals() method

If hash Codes of 2 objects are not equal then .equals() method always return false.(valid)

  
public class Test {
	int i;
	Test(int i) 	{
		this.i=i;
	}
	public int hashCode() 	{
		return i;
	}
	public String toString() 	{
		return i+"";
	}
	public static void main(String[] args) 	{
		Test t1=new Test(10);
		Test t2=new Test(20);
		System.out.println(t1.hashCode());//10
		System.out.println(t2.hashCode());//20
		System.out.println(t1.hashCode()==t2.hashCode());//false
		System.out.println(t1.equals(t2));//false
	}
}

output:

10
20
false
false
  


Contract between .equals() method and hashCode() method

If 2 objects are equal by .equals() method compulsory their hashcodes must be equal (or) same.

 That is If r1.equals(r2) is true then r1.hascode()==r2.hashcode( ) must be true.

If 2 objects are not equal by .equals() method then there are no restrictions on hashCode() methods. 

They may be same (or) may be different. That is If r1.equals(r2) is false then r1.hashCode()==r2.hashCode() may be same (or) may be different.

If hashcodes of 2 objects are equal we can't conclude anything about .equals() method it may return true (or) false.

 That is If r1.hashCode()==r2.hashCode() is true then r1.equals(r2) method may returns true (or) false.

If hashcodes of 2 objects are not equal then these objects are always not equal by .equals() method also.

 That is If r1.hashCode()==r2.hashCode() is false then r1.equals(r2) is always false.

To maintain the above contract between .equals() and hashCode() methods whenever we are overriding .equals() method compulsory we should override hashCode() method. Violation leads to no compile-time error and runtime error but it is not good programming practice.

In this article, We have seen how the Override equals method in java and why it is necessary to Override equals method in java.