Sobes.tech
Junior

What does the equals() method do in Java?

sobes.tech AI

Answer from AI

The equals() method in Java is used to compare objects for equality. By default, in the Object class, it compares references to objects (checks whether two variables point to the same object in memory).

Classes can override the equals() method to implement value-based comparison logic. This means that two different objects are considered equal if their fields or state are equivalent.

When overriding equals(), it is also important to override the hashCode() method, following the contract: if two objects are equal according to equals(), then their hashCode() must be the same.

Example of overriding:

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

    // constructor and getters

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
               Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
What does the equals() method do in Java? — QA / QA… - sobes.tech