Sobes.tech
Middle+

What is the contract between hashCode and equals?

sobes.tech AI

Answer from AI

The contract between hashCode() and equals() in Java requires:

  1. If two objects are equal according to the equals() method, then they must have the same hashCode().
  2. If two objects have the same hashCode(), it does not necessarily mean that they are equal according to equals() (collisions are possible).
  3. The hashCode() method must return the same value on multiple invocations, provided the object has not been modified.

This is important for the correct functioning of hash-based collections (e.g., HashMap, HashSet).

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();
}