Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Compare Two Objects in Java



To compare objects in Java, check the properties or the hash value of given objects. If the properties of both objects matches, then they are equal. If either property is different, it indicate that the objects are not equal.

NOTE: Don't use equality operator (==) to compare objects as it checks only their memory location. Objects comparison should be done based on the properties not location.

How to Compare Objects in Java?

To compare two objects in Java, use the following approaches ?

  • By overriding equals() method
  • Without overriding equals() method
  • Using hashCode() and equals() method

By Overriding equals() Method

By default, equals() method only compares the memory location of objects, i.e., it checks whether the given objects are referring to same object or not. But, we will override this method and put our own logic in it to compare properties of the given object. It returns true if both the objects are same otherwise false.

Example

The following example illustrates how to compare two objects by overriding equals() method.

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;
   }
}

On running the above code, it will produce the following result ?

Are the two objects equal? false

Without Overriding equals() Method

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

Example

In this example, we demonstrates how to compare two objects without overriding equals() method.

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;
   }
}

On executing, this code gives the below output ?

Are the two objects equal? false

Using hashCode() and equals() Methods

The hashCode() method returns the value of hashcode of objects. Hashcode is an integer value that is generated for every object in java. Two similar objects, returns same hash value if both objects are equal as per equals() method otherwise returns different hash value.

Example

In the following example, we are using both hashCode() and equals() methods to compare two objects in Java.

import java.util.*;
class Student {
  String name;
  int regd;
  Student(String name, int regd) { // Constructor
    this.name = name;
    this.regd = regd;
  }
  @Override
  public boolean equals(Object ob) { // overriding equals method
    if (this == ob) {
      return true;
    }
    if (ob == null || this.getClass() != ob.getClass()) {
      return false;
    }
    Student st = (Student) ob;
    // checking equality and returning values of name and regd of objects
    return this.name.equals(st.name) && this.regd == st.regd;
  }
  @Override
    public int hashCode() { // Overriding hashCode method
        return Objects.hash(name, regd);
    }
}
public class Main {
  public static void main(String[] args) {
    Student st1 = new Student("Ansh", 12105);
    Student st2 = new Student("Kumar", 11705);
    Student st3 = new Student("Ansh", 12105);
    if(st1.hashCode() == st2.hashCode()) { // checking hashcode value
        if(st1.equals(st2)) { // checking equality
            System.out.println("st1, st2 objects are same");
        }
    } else if(st1.hashCode() == st3.hashCode()) {
        if(st1.equals(st3)) {
            System.out.println("st1, st3 objects are same"); 
        }
    } else {
        System.out.println("All objects are different");
    }
  }
}

Following the output of the above code ?

st1, st3 objects are same
Updated on: 2024-07-31T19:55:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements