• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Java Program
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » How to Compare two Objects Using hashCode() & Equals()?

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

Last Updated on: August 9, 2022 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Java equals() Method
  • Java equals() Method Without overriding
  • Java equals() Method With Overriding
  • Uniquely identifying objects with a hashcode()
  • Compare Two Objects using HashCode()
  • Compare Two Objects using HashCode() & Equals()

The Object class is the superclass of all Java classes. All java classes implement the Object class by default. The methods provided in the Object class help to compare two objects in Java, using either equals() or hashCode(). In this section, we will learn how these methods work, along with providing examples of how to compare 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 all are the values so based on this value 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 you should 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 to test if two values are equal. The result will be a Boolean value of either true or false.

In order to compare the states of two objects, we can use the equals() method. 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:

In the example below, we’ve created constructors for both the Double and Long classes. These constructors take corresponding values as arguments which are then stored in their respective objects.

In the example below, we’ve created constructors for both the Double and Long classes. These constructors take corresponding values as arguments which are then stored in their respective 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));  
	}
}

In the first println statement, we are invoking the equals() method and passing 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 double class–value1–has the same value as what we inputted into equals().

Java equals() Method Without overriding

The thing is that you need to figure out like let us say if you have an employee object here now employee can have the name, age, and location variables as well. Now how do we compare how they should be equals()? so it depends on our implementation that what we are defining 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 both are equal then that is an equal object right? so this is why it is very important that how we can compare two objects whether they are equal or not.

In Java by default if you want to check the Equality of an object so we have this equals() function where you basically 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 that if you don’t override this equals method it just checks the references that 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

Java equals() Method With Overriding

Let’s say I don’t want to check only the reference but I want to check the actual values like name and age are matching or not. if both name and age are matching then both employers are equals. so how we can 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

Uniquely identifying objects with a hashcode()

When we use the hashcode() method to compare objects, it makes our life much easier by returning 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 are different, 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 also identical.

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.

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:

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

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers