Sobes.tech
Middle

What is the contract between equals() and hashCode()?

sobes.tech AI

Answer from AI

The contract between the equals() and hashCode() methods in Java states:

  • If two objects are equal according to equals(), then they must have the same hashCode().
  • If the hashCode() of two objects is different, then equals() must return false.
  • If the hashCode() is the same, equals() can return either true or false (hash collisions are allowed).

This is important for the correct functioning of hash-based collections (e.g., HashMap, HashSet). Violating the contract can lead to incorrect behavior — for example, an object might not be found in a hash table.

Example:

@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 field.hashCode();
}

Here, equals compares the field, and hashCode returns the hash of the same field, ensuring consistency.