Middle+
What is the contract between hashCode and equals?
sobes.tech AI
Answer from AI
The contract between hashCode() and equals() in Java requires:
- If two objects are equal according to the
equals()method, then they must have the samehashCode(). - If two objects have the same
hashCode(), it does not necessarily mean that they are equal according toequals()(collisions are possible). - 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();
}