Sobes.tech
Junior — Middle

What is the purpose of the equals() method in Java?

sobes.tech AI

Answer from AI

The equals() method in Java is used to compare objects for equality based on content, not reference. By default, the equals() method in the Object class compares references (i.e., checks if two variables point to the same object).

By overriding equals(), you can define that two objects are considered equal if certain fields match. This is important, for example, when working with collections where objects need to be compared by value.

Example of overriding equals() in the Person class:

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

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

Thus, equals() allows comparing objects based on logic rather than memory address.