Sobes.tech
Junior — Middle

Could you explain the purpose of the equals method in Java and how it is used for object comparison?

sobes.tech AI

Answer from AI

The equals method in Java is used to compare objects for logical equality, i.e., to determine whether two objects are considered equivalent by their content rather than by reference.

By default, the equals method is inherited from the Object class and compares references (checks if two variables point to the same object). To compare objects by value, classes override this method.

Example of overriding equals for a 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 other = (Person) obj;
        return age == other.age && Objects.equals(name, other.name);
    }

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

Using equals allows comparing objects by content, which is important for collections, searching, and other operations.

Could you explain the purpose of the equals method in… - sobes.tech