Java Program to Compare Two Objects
Last Updated :
16 Jun, 2021
An object is an instance of a class that has its state and behavior. In java, being object-oriented, it is always dynamically created and automatically destroyed by the garbage collector as the scope of the object is over.
Illustration: An example to illustrate an object of a class:
Furniture chair=new Furniture();
Furniture sofa=new Furniture();
// Here, chair and sofa are two objects of the class Furniture
Approaches:
There are two standard methods:
- Using equals()
- Without overriding
- With overriding
- Using hashCode() and equals() method
Example 1: Although equals() method can be used to compare the values of two strings, it is not really useful by default to compare two objects without overriding it.
Java
// Java Program to compare two objects
// Importing java input output library
import java.io.*;
// Class 1
class Pet {
// attributes of class1
String name;
int age;
String breed;
// constructor of class 1
Pet(String name, int age, String breed)
{
// Assignment of current attributes
/// using this keyword with same
this.name = name;
this.age = age;
this.breed = breed;
}
}
/* Class 2 : where execution is shown
for class 1 */
public class GFG {
// Main driver method
public static void main(String args[])
{
// Objects of class1 (auxiliary class)
// are assigned value */
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
// Checking objects are equal and
// printing output- true/false
System.out.println(dog1.equals(dog2));
}
}
Example 2: Overriding equals() method
Though the values of dog1 and dog2 are the same, equals() method always checks the reference of the two objects i.e if both the objects passed refer to the same object or not and not their values. Therefore, it is advisable not to use this method in comparing objects without overriding it. Implementing the equals method for the before example:
Java
// Java Program to Compare Two Objects
import java.io.*;
class Pet {
String name;
int age;
String breed;
Pet(String name, int age, String breed)
{
this.name = name;
this.age = age;
this.breed = breed;
}
@Override public boolean equals(Object obj)
{
// checking if the two objects
// pointing to same object
if (this == obj)
return true;
// checking for two condition:
// 1) object is pointing to null
// 2) if the objects belong to
// same class or not
if (obj == null
|| this.getClass() != obj.getClass())
return false;
Pet p1 = (Pet)obj; // type casting object to the
// intended class type
// checking if the two
// objects share all the same values
return this.name.equals(p1.name)
&& this.age == p1.age
&& this.breed.equals(p1.breed);
}
}
public class GFG {
public static void main(String args[])
{
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
System.out.println(dog1.equals(dog2));
}
}
Example 3: In the above example, the equals() method is checking if all the values match or not. However, it can be overridden in any way possible i.e if one or two values match, etc. For example, if we want to check for any two values to make the equals() method consider the two objects to be the same:
Java
// Java Program to Compare Two Objects
// Importing java input/output libraries
import java.io.*;
// Class 1
class Pet {
// Attributes of objects
String name;
int age;
String breed;
// Constructor
Pet(String name, int age, String breed)
{
// Assigning current there it self
// using this keyword
this.name = name;
this.age = age;
this.breed = breed;
}
@Override public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null
|| this.getClass() != obj.getClass())
return false;
Pet p1 = (Pet)obj;
// Checking only if attribute- name
// and age is same and ignoring breed
return this.name.equals(p1.name)
&& this.age == p1.age;
}
}
public class GFG {
// Main driver method
public static void main(String args[])
{
// Assigning values to attributes of object
// of class 1
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat1 = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
Pet cat2 = new Pet("Jack", 2, "Persian");
// Checking if object are equal and
// printing boolean output
System.out.println(cat1.equals(cat2));
}
}
Using hashCode() and equals()
This method is more like an add-on to the previous one. Checking the hash values using hashCode() before entering the equals() reduces the time taken to produce the solution drastically. In this way, many comparisons between two objects need not go through the comparison of every value within them.
Example 1: The above implementation along with usage of hashCode():
Java
// Java Program to Compare Two Objects
// Importing java input/output libraries
import java.io.*;
// Class 1
class Pet {
// Attributes of objects of class
String name;
int age;
String breed;
// Constructor
Pet(String name, int age, String breed)
{
this.name = name;
this.age = age;
this.breed = breed;
}
// Overriding using hashCode() method
@Override public int hashCode()
{
/* overriding hashCode() method
to check the length of the names */
return this.name.length() % 10;
}
// Boolean function to check
@Override public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null
|| this.getClass() != obj.getClass())
return false;
Pet p1 = (Pet)obj;
return this.name.equals(p1.name)
&& this.age == p1.age && this.breed == p1.breed;
}
}
// main class (class2)
public class GFG {
// Main driver method
public static void main(String args[])
{
// Assigning values to object of class 1(Pet class)
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat1 = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
Pet cat2 = new Pet("Jack", 2, "Persian");
/* hashCode() generates true as the lengths of
the name value of the two objects are same*/
// Condition check using hashCode() method
if (dog1.hashCode() == cat1.hashCode())
/* On entering equals() method, it checks for
other values and hence, returns false */
System.out.println(dog1.equals(cat1));
else
System.out.println("Not equal");
}
}
Example 2:
Java
// Java Program to Compare Two Objects
import java.io.*;
class Pet {
String name;
int age;
String breed;
Pet(String name, int age, String breed)
{
this.name = name;
this.age = age;
this.breed = breed;
}
@Override public int hashCode()
{
// overriding hashCode() method to first
// check the length of the names*/
return this.name.length() % 10;
}
@Override public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null
|| this.getClass() != obj.getClass())
return false;
Pet p1 = (Pet)obj;
return this.name.equals(p1.name)
&& this.age == p1.age && this.breed == p1.breed;
}
}
public class GFG {
public static void main(String args[])
{
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat1 = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
Pet cat2 = new Pet("Jack", 2, "Persian");
Pet dog3 = new Pet("Ray", 1, "Siberian Husky");
// here, hashCode() generates false and condition
// reverts to the else statement as soon as it finds out
// the lengths of the name value of the objects are
// differenT
if (dog1.hashCode() == dog3.hashCode())
System.out.println(dog1.equals(dog3));
else
System.out.println("Not equal");
}
}
Similar Reads
How to Compare Two TreeMap Objects in Java? TreeMap class in java provides a way of storing key-value pairs in sorted order. The below example shows how to compare two TreeMap objects using the equals() method. It compares two TreeMap objects and returns true if both of the maps have the same mappings else returns false. Syntax: boolean equal
1 min read
Java Program to Compare two Boolean Arrays Two arrays are equal if they contain the same elements in the same order. In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is .equals() method.By using the Naive approach. Examples: Input : A = [true , true , false] A1 = [true, true, false] Output: Both the ar
3 min read
How to Override compareTo() Method in Java? As we know, there are basically two types of sorting technique in Java:First is internal sorting i.e that uses predefined sorting method ascending order Arrays.sort() for Primitive class arrays and wrapper class arrays and Collections.sort() for collections both methods sort the elements in ascendin
4 min read
How to Compare Objects by Multiple Fields in Java? In Java, A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class. In this article, we will learn how to compare objects by multiple fields. Compare Objects by Multiple FieldsTo compare objects by multiple
3 min read
How to Compare two Collections in Java? Java Collection provides an architecture to store and manipulate the group of objects. Here we will see how to compare Elements in a Collection in Java. Steps: Take both inputs with help of asList() function.Sort them using Collections.sort() method.Compare them using equals() function.Print output.
2 min read
Comparing two ArrayList In Java Java provides a method for comparing two Array List. The ArrayList.equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal. Example: Input : ArrayLis
2 min read
Check if Two Integers are Equal or Not in Java Checking two integers equal or not in Java is done by various approaches. Arithmetic operatorComparison OperatorsString functionsXOR operatorComplement (~) and bit-wise (&) operator Example Input: FirstNumber = 15 SecondNumber= 15 Output: Numbers are same Input: FirstNumber = 15 SecondNumber= 25
2 min read
Java String equals() Method String equals() method in Java compares the content of two strings. It compares the value's character by character, irrespective of whether two strings are stored in the same memory location. The String equals() method overrides the equals() method of the object class. false if any of the characters
2 min read
EnumMap equals() Method in Java with Examples The Java.util.EnumMap.equals(obj) in Java is used to compare the passed object with this EnumMap for the equality. It must be kept in mind that the object passed must be a map of the same type as the EnumMap.Syntax: boolean equals(Object obj) Parameter: The method takes one parameter obj of Object t
2 min read