Skip to content
Preptima
mediumConceptCodingEntryMidSenior

If you override equals but not hashCode, what breaks and when?

Equal objects must produce equal hash codes. Break that and a HashMap sends lookups to a bucket the entry was never placed in, so the map holds a value you can no longer retrieve and a set silently admits duplicates. The same failure appears later if a key is mutated after insertion.

4 min readUpdated 2026-08-15

Answer

Short answer

In Java, equals() and hashCode() must agree: if two objects are equal, they must return the same hash code. If you override equals() without a matching hashCode(), hash-based collections place and search the objects in different buckets, so HashMap.get, HashSet.contains, and deduplication silently fail. The fields used by both methods should also be stable while the object is used as a key.

Was this answer helpful?

Likely follow-ups

  • Why is a mutated key a memory leak and not just a failed lookup?
  • BigDecimal treats 1.0 and 1.00 as unequal under equals but equal under compareTo. What does that do to a HashSet versus a TreeSet?
  • How would you write equals for a JPA entity whose ID is database-generated?
  • Does a record's generated equals do the right thing for every component type?

Related questions

Further reading

Related Topics