Sobes.tech
Junior

What does the equals() method do?

sobes.tech AI

Answer from AI

The equals() method in Java compares two objects for equality.

By default (in the Object class), it checks whether the references to the objects are the same (whether they point to the same instance in memory).

Classes can override this method to define logical equality of objects based on their content (for example, two String objects are considered equal if they contain the same sequence of characters, even if they are different instances).

When overriding equals(), it is also necessary to override the hashCode() method to adhere to the contract: if two objects are equal according to equals(), then their hashCode() methods must return the same value.

Example of overriding:

class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // Reference comparison
        if (o == null || getClass() != o.getClass()) return false; // Null check and class comparison
        MyClass myClass = (MyClass) o; // Type casting
        return value == myClass.value; // Logical comparison based on the value field
    }

    @Override
    public int hashCode() {
        return Objects.hash(value); // Hash code generation
    }
}