Compare objects in Java

To compare objects in Java, you need to override the equals() and hashCode() methods of the object's class. Here's an example code snippet that demonstrates object comparison:


public class Person {
    private String name;
    private int age;

    // Constructors, getters, and setters

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;

        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

In the above code, the Person class has two attributes: name and age. The equals() method compares the name and age attributes of two Person objects to determine if they are equal. The hashCode() method generates a hash code based on the name and age attributes.


Here's an example usage of the Person class:

public class ObjectComparisonExample {
    public static void main(String[] args) {
        Person person1 = new Person("Alice", 25);
        Person person2 = new Person("Alice", 25);
        Person person3 = new Person("Bob", 30);

        // Comparing person1 and person2
        System.out.println("person1.equals(person2): " + person1.equals(person2)); // true

        // Comparing person1 and person3
        System.out.println("person1.equals(person3): " + person1.equals(person3)); // false

        // Comparing person2 and person3
        System.out.println("person2.equals(person3): " + person2.equals(person3)); // false
    }
}

In the above code, we create three Person objects: person1, person2, and person3. We then compare these objects using the equals() method, which will return true if the name and age attributes are the same, and false otherwise.

Note that when overriding equals(), you should also override the hashCode() method to maintain the contract between these two methods. The hashCode() method is used when storing objects in hash-based collections like HashMap or HashSet.