Sobes.tech
Senior

Tell me about the equals/hashCode contract.

sobes.tech AI

Answer from AI

The equals and hashCode contract in Java is an agreement that guarantees the correct functioning of objects in collections, especially in hash-based structures (e.g., HashMap, HashSet).

Main rules of the contract:

  • If two objects are equal according to the equals() method, they must have the same hashCode().
  • If equals() returns false for two objects, their hashCode() can be different, but they can also be the same (collisions are allowed).
  • The equals() method must be:
    • Reflexive: x.equals(x) is always true.
    • Symmetric: x.equals(y) is equal to y.equals(x).
    • Transitive: if x.equals(y) and y.equals(z), then x.equals(z).
    • Consistent: multiple calls return the same result if objects are not modified.
    • Not equal to null: x.equals(null) is always false.

Example implementation:

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

@Override
public int hashCode() {
    return Objects.hash(field1, field2);
}

Breaking this contract can lead to errors when working with collections, for example, an object may not be found in a HashSet or HashMap even if it is logically equal to another object.

Tell me about the equals/hashCode contract. — Java - sobes.tech