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
Java Program to Sort Objects in ArrayList by Date
The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Com
6 min read
Java Program to Sort LinkedList using Comparable
In Java, LinkedList is a part of the collection framework provided in java.util package. LinkedList is a linear data structure where all the elements are unsorted in contiguous memory locations. The advantage of LinkedList is it is dynamic and easy to insert and delete any element. We can not access
5 min read
Comparing Path of Two Files in Java
The path of two files can be compared lexicographically in Java using java.io.file.compareTo() method. It is useful to raise a Red Flag by the operating system when the program is requesting the file modification access which is already in use by another program. To compare the path of the file, com
2 min read
Java Program to Sort ArrayList of Custom Objects By Property
Here we are going to look at the approach of sorting an ArrayList of custom objects by using a property. Approach: 1. Create a getter function which returns the value stored in the class variable. 2. Create a list and use sort() function which takes the values of the list as arguments and compares t
2 min read
Java Program To Check If Two Linked Lists Are Identical
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE
3 min read
Java Object Oriented Programming - Exercises
Looking for Java OOP exercises to test and improve your object-oriented programming skills? Explore our topic-wise Java OOP practice exercises, featuring over 25 practice problems designed to help you master key OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction. Java is
15+ min read
Java Program For Comparing Two Strings Represented As Linked Lists
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicograph
2 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