Java Program to Compare Two Objects


Introduction

In Java, objects can be compared using the equals() method, which checks whether two objects are equal based on their properties. When comparing objects in Java, it is important to override the equals() method in the class to ensure that the comparison is done based on the desired properties.

This Java program compares two objects of type Person by overriding the equals() method to compare the objects based on their name and age properties. The equals() method is first used to check if the objects are of the same class and then compares the name and age properties. If both properties match, the method returns true, indicating that the objects are equal. If either property is different, the method returns false, indicating that the objects are not equal.

Methods

There are two Standard Methods

  • Using equals()

    • Without overriding

    • With overriding

  • Using hashCode() and equals() method

Example 1: Overriding equals() Method

Overriding equals() method in a class allows custom comparison of objects based on their properties.

Approach

  • We first define a Person class with two private instance variables: name and age.

  • We define a constructor for the Person class that takes in a name and age and initializes the instance variables with these values.

  • We override the equals() method in the Person class to compare two Person objects based on their name and age. The equals() method takes in an Object parameter, which we first check to make sure is not null and is an instance of the Person class. We then cast the object to a Person object and compare its name and age properties to the current object's name and age properties.

  • In the main() method, we create two Person objects with different name and age values.

  • We call the equals() method on the first Person object, passing in the second Person object as a parameter. The equals() method returns a boolean value indicating whether the two objects are equal.

  • Finally, we print out the result of the comparison to the console using System.out.println()

public class ObjectComparator {
    
   public static void main(String[] args) {
        
      // Create two objects to compare
      Person person1 = new Person("Alice", 25);
      Person person2 = new Person("Bob", 30);
        
      // Compare the two objects
      boolean areEqual = person1.equals(person2);
      System.out.println("Are the two objects equal? " + areEqual);
   }
}

class Person {
    
   private String name;
   private int age;
    
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
    
   @Override
   public boolean equals(Object obj) {
      if (obj == null) return false;
      if (!(obj instanceof Person)) return false;
      Person otherPerson = (Person) obj;
      return this.name.equals(otherPerson.name) && this.age == otherPerson.age;
   }
}

Explanation

In this example, we create two Person objects with different names and ages, and then call the equals method on the first object to compare it to the second object. The equals method is defined in the Person class and checks if the two objects have the same name and age properties. Finally, we print out the result of the comparison to the console.

Output

Are the two objects equal? false

Example 2: Without Overriding equals() Method

Without overriding equals() method, objects are compared based on their reference, not their properties.

Approach

  • We first define a Person class with two private instance variables: name and age.

  • We define a constructor for the Person class that takes in a name and age and initializes the instance variables with these values.

  • In the main() method, we create two Person objects with the same name and age values.

  • We call the equals() method on the first Person object, passing in the second Person object as a parameter. Since we haven't overridden the equals() method in the Person class, the default implementation of equals() inherited from the Object class is used. This implementation checks if the two objects are the same object (i.e., have the same memory address) and returns true if they are. Since the person1 and person2 objects have different memory addresses, the equals() method returns false.

  • Finally, we print out the result of the comparison to the console using System.out.println().

public class ObjectComparator {
    
   public static void main(String[] args) {
        
      // Create two objects to compare
      Person person1 = new Person("Alice", 25);
      Person person2 = new Person("Alice", 25);
        
      // Compare the two objects
      boolean areEqual = person1.equals(person2);
      System.out.println("Are the two objects equal? " + areEqual);
   }
}

class Person {
    
   private String name;
   private int age;
    
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
}

Explanation

In this example, we create two Person objects with the same name and age, and then call the equals method on the first object to compare it to the second object. Since we haven't overridden the equals method in the Person class, the default implementation of equals inherited from the Object class is used. This implementation checks if the two objects are the same object (i.e., have the same memory address) and returns true if they are. Since the person1 and person2 objects have different memory addresses, the equals method returns false. Finally, we print out the result of the comparison to the console.

Output

Are the two objects equal? false

Example 3: Using hashCode() and equals() Method

Without overriding equals() method, objects are compared based on their reference, not their properties.

Approach

  • We create two objects of the Person class, person1 and person2, with the same name and age.

  • We then call the hashCode() and equals() methods on person1.

  • In the Person class, we override the hashCode() method to generate a hash code based on the object's name and age properties using the Objects.hash() method.

  • We then override the equals() method to compare two Person objects based on their name and age properties. The method checks if the objects are of the same class, and if so, checks if their name and age properties are equal using the Objects.equals() method.

  • In the main() method, we use the && operator to check if the hash codes of person1 and person2 are the same using the hashCode() method and if the equals() method returns true.

  • Finally, we print out a message indicating whether the objects are equal or not.

public class ObjectComparator {
    
   public static void main(String[] args) {
        
      // Create two objects to compare
      Person person1 = new Person("Alice", 25);
      Person person2 = new Person("Alice", 25);
        
      // Compare the two objects using hashCode and equals methods
      boolean areEqual = person1.hashCode() == person2.hashCode() && person1.equals(person2);
      System.out.println("Are the two objects equal? " + areEqual);
   }
}

class Person {
    
   private String name;
   private int age;
    
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
    
   @Override
   public int hashCode() {
      return Objects.hash(name, age);
   }
    
   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (!(obj instanceof Person))
         return false;
      Person other = (Person) obj;
      return Objects.equals(name, other.name) && age == other.age;
   }
}

Explanation

In this example, we create two Person objects with the same name and age, and then call the hashCode() and equals() methods on the first object to compare it to the second object.

In the Person class, we override the hashCode() and equals() methods to compare the objects based on their name and age properties. The hashCode() method returns the hash code of a combination of the name and age properties, and the equals() method checks if the objects are of the same class and have the same name and age properties.

Finally, we use the && operator to check if the hash codes of the two objects are the same and if the equals() method returns true. If both conditions are true, we print out that the objects are equal. Otherwise, we print out that the objects are not equal.

Output

The two person objects are equal

Conclusion

  • The Java program compares two Person objects based on their properties using the equals() method, which has been overridden in the Person class.

  • The program demonstrates the importance of customizing object comparison and highlights the flexibility provided by Java in implementing custom comparison logic.

Updated on: 14-Jul-2023

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements