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 samehashCode(). - If
equals()returnsfalsefor two objects, theirhashCode()can be different, but they can also be the same (collisions are allowed). - The
equals()method must be:- Reflexive:
x.equals(x)is alwaystrue. - Symmetric:
x.equals(y)is equal toy.equals(x). - Transitive: if
x.equals(y)andy.equals(z), thenx.equals(z). - Consistent: multiple calls return the same result if objects are not modified.
- Not equal to
null:x.equals(null)is alwaysfalse.
- Reflexive:
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.