Junior — Middle
Why is it important to maintain consistency between the equals and hashCode methods when overriding them?
sobes.tech AI
Answer from AI
In Java, the methods equals and hashCode are closely related: if two objects are considered equal according to equals, then their hashCode should return the same value. This is important for the correct functioning of hash-based collections, such as HashMap or HashSet. If this rule is violated, objects may be stored incorrectly or not found in such collections, leading to errors and hard-to-detect bugs.
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 id == myClass.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
Here, equals compares based on the id field, and hashCode is also based on this field, ensuring consistency.