Q10: What is the equals() and hashCode() contract, and why must both be overridden together?
The contract dictates:
- If
a.equals(b)istrue, thena.hashCode() == b.hashCode()MUST betrue. - If
a.hashCode() == b.hashCode(),a.equals(b)may or may not betrue(hash collision). If you override.equals()without.hashCode(), key lookups in hash-based collections (HashMap,HashSet) will fail because duplicate objects resolve to different bucket indices.
Overriding equals and hashCode
public class Person {
private final int id;
private final String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person person)) return false;
return id == person.id && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}💡 Both methods evaluate the exact same identity fields to satisfy the Java collection contract.
Key Takeaways
- Equal objects MUST have equal hash codes.
- Failing to override
hashCode()breaksHashMapandHashSetlookups.
Knowledge Check
What happens if two distinct instances return the exact same hashCode() value?