Sobes.tech
Junior — Middle

Explain the working principle of the equals method and its role in object comparison.

sobes.tech AI

Answer from AI

The equals method in Java is used to compare objects for logical equality, meaning checking whether two objects represent the same thing in terms of content, rather than just referencing the same object in memory (as the == operator does).

By default, the equals method is inherited from the Object class and compares references (acting like ==). To make the comparison meaningful, classes override this method, taking into account the values of the object's fields.

Example of overriding the equals method:

@Override
public boolean equals(Object obj) {
    if (this == obj) return true; // reference comparison
    if (obj == null || getClass() != obj.getClass()) return false;
    MyClass other = (MyClass) obj;
    return Objects.equals(field1, other.field1) && field2 == other.field2;
}

The role of the equals method is important when working with collections (e.g., HashSet, HashMap), where it is necessary to determine if objects are equal for correct storage and retrieval.

Important: When overriding equals, it is also recommended to override hashCode to maintain the contract between these methods.