Junior — Middle
How to correctly implement the hashCode and equals methods in a class?
sobes.tech AI
Answer from AI
The hashCode and equals methods in Java should be implemented so that:
- If two objects are equal according to
equals(), then theirhashCode()must also be equal. equals()should be reflexive, symmetric, transitive, and consistent.
Example of correct implementation for a class with two fields id and name:
@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(id, myClass.id) && Objects.equals(name, myClass.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
Use Objects.equals and Objects.hash for convenience and null safety. The implementation should consider all fields that influence the logical equality of objects.