Junior — Middle
Why is it recommended to override the equals and hashCode methods simultaneously in Java?
sobes.tech AI
Answer from AI
In Java, it is recommended to override the equals() and hashCode() methods simultaneously because they are linked by a contract:
- If two objects are considered equal according to equals(), they must have the same hashCode().
- If hashCode() is not overridden along with equals(), objects that are equal according to equals() may have different hash codes, leading to incorrect behavior of hash-based collections (e.g., HashMap, HashSet).
Example:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return Objects.equals(field, other.field);
}
@Override
public int hashCode() {
return Objects.hash(field);
}
Thus, following this rule ensures correct behavior of objects in collections and prevents hard-to-detect errors.