Sobes.tech
Junior — Middle

Why is it necessary to override the equals() and hashCode() methods together in Java, and how does this affect collection operations?

sobes.tech AI

Answer from AI

In Java, the methods equals() and hashCode() are linked by a contract that guarantees the correct functioning of objects in collections, especially those based on hashing (e.g., HashMap, HashSet).

If you override equals() but not hashCode(), objects considered equal by equals() may have different hash codes. This will cause hash-based collections to behave incorrectly: for example, an object may not be found in a HashSet even though it logically exists there.

The contract states:

  • If two objects are equal according to equals(), they must have the same hashCode().
  • If hashCode() of objects is different, they are definitely not equal.

Example of overriding:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    MyClass myClass = (MyClass) o;
    return field.equals(myClass.field);
}

@Override
public int hashCode() {
    return Objects.hash(field);
}

Thus, overriding both methods together ensures the correct behavior of objects in collections.