Google News
logo
How to Compare Two Objects in Java
In Java, we can compare two objects using either the equals() method or the compareTo() method. Here's how to use each method:

equals() method :

The equals() method is used to check if two objects are equal in value. It returns a boolean value true if the objects are equal and false otherwise. By default, the equals() method compares the memory addresses of the objects. To compare the contents of the objects instead, you need to override the equals() method in the class definition.

For example, let's say we have a class Person with two instance variables name and age. We can override the equals() method in the Person class to compare the name and age variables :
Program :
public class Person {
    private String name;
    private int age;

    // constructor, getter and setter methods

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof Person)) {
            return false;
        }

        Person p = (Person) o;

        return name.equals(p.name) && age == p.age;
    }
}
In this implementation of the equals() method, we first check if the objects are the same using the == operator. If they are, we return true. We then check if the object is an instance of the Person class. If it is not, we return false.

Finally, we cast the object to a Person object and compare the name and age variables using the equals() method and the == operator, respectively.

compareTo() method :

The compareTo() method is used to compare two objects and returns an integer value that indicates the relationship between the objects. It returns a negative integer if the first object is less than the second object, zero if they are equal, and a positive integer if the first object is greater than the second object.

To use the compareTo() method, the class of the objects being compared must implement the Comparable interface and define the compareTo() method in the class definition.

For example, let's say we have a class Person with an instance variable age. We can implement the Comparable interface in the Person class to compare the ages of two Person objects:
Program :
public class Person implements Comparable<Person> {
    private String name;
    private int age;

    // constructor, getter and setter methods

    @Override
    public int compareTo(Person p) {
        return Integer.compare(age, p.age);
    }
}
In this implementation of the compareTo() method, we compare the age variable of the two Person objects using the Integer.compare() method, which returns a negative integer if the age of the first object is less than the age of the second object, zero if they are equal, and a positive integer if the age of the first object is greater than the age of the second object.