How to Compare two Objects Using hashCode() & Equals()?

The Object class is the superclass of all Java classes. All the Java classes implement the Object class by default. The methods provided in the Object class help to compare two objects in Java, using either the equals() or hashCode() method. In this section, we will learn how these methods work and provide examples of comparing two objects in Java.

Whenever we want to compare the primitive data type (int, float, long, double), we can always compare using this == operator, and then it will compare and give us the result. Because these are all the values, based on these values, it will compare which is greater and which is smaller. But the point is that if there are objects now on which value and how should you compare?

Post Type:Core Java Tutorial
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

For comparing objects, Java provides two methods, and that is:

  • Java equals() Method – Without overriding & With overriding
  • Java hashcode() Method

Java equals() Method

The comparison operator == can be used when dealing with primitive data types like int, float, long, and double to test if two values are equal. The result will be a Boolean value of either true or false.

We can use the equals() method to compare the states of two objects. However, we have to adapt it by overwriting it. This means that we have to define how exactly the objects should be compared in order for them to be considered equal.

Example 1: Java equals() Method

In the example below, we’ve created double and long-class constructors. These constructors take corresponding values as arguments and store them in their objects.

package com.softwaretestingo.basic;
public class SimpleObjectComparisonExample 
{
	public static void main(String[] args) 
	{
		// Creating Constructor of the Double class   
		Double value1 = new Double(111.222);  

		// Creating constructor of the Long class   
		Long value2 = new Long(33333);  

		//invoking the equals() method   
		System.out.println("Objects are not equal, hence it returns: " + value1 .equals(value2));  
		System.out.println("Objects are equal, hence it returns:  " + value1.equals(111.222));  
	}
}
Objects are not equal, hence it returns: false
Objects are equal, hence it returns:  true

In the first println statement, we invoke the equals() method and pass an object value2 as a parameter that compares with the object value1. It returns false because value1 holds a double value, and value2 holds a long value, which is not equal.

Likewise, in the second println statement, we have used the equals() method and passed in the same value as what is in the constructor of the Double class. This returns true because the object of the double class and value1 has the same value as what we inputted into equals().

Example 2: Java equals() Method Without overriding

We need to figure out, like, let us say, if you have an employee object here, now the employee can have the name, age, and location variables as well. Now, how do we compare, and how should they be equal? So, it depends on our implementation of what we define or what parameters are equal for a particular object.

So basically, we can say if their name is equal, then they are equal, or if their name and age are equal, that is an equal object, right? This is why comparing two objects to determine whether they are equal is very important.

In Java, by default, if you want to check the Equality of an object, we have this equals() function where we provide the first object, and then you have to pass the second object as a parameter to the equals method.

So now, by default, what happens is that if you don’t override this equals method, it just checks the references to see whether they are referring to the same objects or not, and according to that, it will give you the result.

package com.softwaretestingo.basic;
//Class 1
class employee 
{
	// attributes of class1
	String name;
	int age;
	String location;

	// constructor of class 1
	employee(String name, int age, String location)
	{
		// Assignment of current attributes using this keyword with same
		this.name = name;
		this.age = age;
		this.location = location;
	}
}

/* Class 2 : where execution is shown for class 1 */
public class ObjectComparisonExamplewithEqual1  
{
	// Main driver method
	public static void main(String args[])
	{

		// Objects of class1 (auxiliary class)
		// are assigned value */
		employee emp1 = new employee("Harish", 25, "Bangalore");
		employee emp2 = new employee("Ram", 28, "Hyderabad");
		employee emp3 = new employee("Swati", 23, "Noida");

		// Checking objects are equal and printing output- true/false
		System.out.println(emp1.equals(emp3));
	}
}
false

Example 3: Java equals() Method With overriding

Let’s say I don’t want to check only the reference, but I want to check whether the actual values like name and age match. If both name and age match, then both employers are equal. So how can we do that? In this case, we need to override this equals() method.

package com.softwaretestingo.Basic;
class employeer
{
	// attributes of class1
	String name;
	int age;
	String location;

	// constructor of class
	employeer(String name, int age, String location)
	{
		// Assignment of current attributes using this keyword with same
		this.name = name;
		this.age = age;
		this.location = location;
	}
	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (obj == null || this.getClass() != obj.getClass())
			return false;
		employeer p1 = (employeer)obj;

		// Checking only if attribute- name & age and ignore lcoation
		return this.name.equals(p1.name) && this.age == p1.age;
	}
}
public class ObjectComparisonExamplewithOverrideEqual 
{
	// Main driver method
	public static void main(String args[])
	{
		// assigning value */
		employeer emp1 = new employeer("Harish", 25, "Bangalore");
		employeer emp2 = new employeer("Harish", 25, "Hyderabad");

		// Checking objects are equal and printing output- true/false
		System.out.println(emp1.equals(emp2));
	}
}
true

Explanation Of the Above Program:

  • The program defines a class named “employeer” with three attributes: name, age, and location. It also has a constructor that initializes these attributes.
  • The employeer class overrides the equals() method, which is a method inherited from the Object class. The program compares the current object with the passed object using the “==” operator in the overridden method. If they are equal, it returns true. If the passed object is null or its class is not the same as the current object’s class, it returns false.
  • The program then creates two employeer objects, emp1, and emp2, with the same name and age but different locations.
  • Finally, the program calls the equals() method on emp1 with emp2 as the argument and prints the result. The equals() method only checks if the name and age attributes are equal and ignores the location attribute. Therefore, the program’s output is “true” because the name and age attributes of emp1 and emp2 are the same.

Uniquely identifying objects with a hashcode()

We can also use the hashcode() method to compare objects. This method is easier because it returns a unique ID for each object. This allows us to quickly compare the state of all objects in our program and makes our lives much easier!

If the hashcodes of two objects differ, there is no need to run the equals() method to compare them – you already know they aren’t equal. However, if the hashcodes are the same, you must use equals() to check if the values and fields within the objects are identical.

Example 4: Compare Two Objects using HashCode()

package com.softwaretestingo.basic;
class employeer1
{
	// attributes of class1
	String name;
	int age;
	String location;

	// constructor of class
	employeer1(String name, int age, String location)
	{
		// Assignment of current attributes using this keyword with same
		this.name = name;
		this.age = age;
		this.location = location;
	}
	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (obj == null || this.getClass() != obj.getClass())
			return false;
		employeer2 p1 = (employeer2)obj;

		// Checking only if attribute- name & age and ignore lcoation
		return this.name.equals(p1.name)
				&& this.age == p1.age;
	}
}
public class ObjectComparisonExamplewithHashcode  
{
	// Main driver method
	public static void main(String args[])
	{
		// assigning value */
		employeer2 emp1 = new employeer2("Harish", 25, "Bangalore");
		employeer2 emp2 = new employeer2("Harish", 25, "Hyderabad");
		System.out.println(emp1.hashCode());
		System.out.println(emp2.hashCode());
		boolean isHashcodeEquals = emp1.hashCode() == emp2.hashCode();

		if (isHashcodeEquals) 
		{
			System.out.println("Should compare with equals method too.");
		} 
		else
		{
			System.out.println("Should not compare with equals method because " +
					"the id is different, that means the objects are not equals for sure.");
		}
	}
}
2018699554
1311053135
Should not compare with equals method because the id is different, that means the objects are not equals for sure.

Example 5: Compare Two Objects using HashCode() & Equals()

package com.softwaretestingo.basic;
class employeer2
{
	// attributes of class1
	String name;
	int age;
	String location;

	// constructor of class
	employeer2(String name, int age, String location)
	{
		// Assignment of current attributes using this keyword with same
		this.name = name;
		this.age = age;
		this.location = location;
	}
	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (obj == null
				|| this.getClass() != obj.getClass())
			return false;
		employeer2 p1 = (employeer2)obj;

		// Checking only if attribute- name & age and ignore lcoation
		return this.name.equals(p1.name)
				&& this.age == p1.age;
	}
}
public class ObjectComparisonExamplewithHashcodeEqual  
{
	// Main driver method
	public static void main(String args[])
	{
		// assigning value */
		employeer2 emp1 = new employeer2("Harish", 25, "Bangalore");
		employeer2 emp2 = new employeer2("Harish", 25, "Hyderabad");
		System.out.println("EMP1 Hashocde: "+emp1.hashCode());
		System.out.println("EMP2 Hashocde: "+emp2.hashCode());

		if (emp1.equals(emp2)) 
		{
			System.out.println("Should compare with equals method too.");
		} 
		else
		{
			System.out.println("Should not compare with equals method because " +
					"the id is different, that means the objects are not equals for sure.");
		}
	}
}
EMP1 Hashocde: 2018699554
EMP2 Hashocde: 1311053135
Should compare with equals method too.

Conclusion:

After going through all the Compare Two Objects Java programs, I hope you can understand how to Compare two Objects. If you still have any issues understanding, let us know in the comment section, and we will try to clarify as soon as possible.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment