Fundamentals · Hard · Free
Why must equals() and hashCode() stay consistent in Java?
FresherFundamentalsOOP & Language Fundamentals
equals and hashCode contract
If two objects are equal per equals(), they must have the same hashCode. Violating this breaks HashMap/HashSet—objects become "lost" in buckets.
java
@Override public boolean equals(Object o) {
if (!(o instanceof User u)) return false;
return id.equals(u.id);
}
@Override public int hashCode() { return Objects.hash(id); }Say you use IDE generate or
Objects.hash—never override equals without hashCode.