Skip to the page

Objects and language basics · core

equals, hashCode and objects in hash collections

If two objects are equal, they must have the same hash code. Break that, or change a key field after adding it to a set, and objects get lost in HashSet and HashMap.

The notes

What you must know

  • Contract: if a.equals(b) is true then a.hashCode() == b.hashCode(). The reverse is not required: different objects may share a hash code. That only costs speed.
  • equals must be reflexive, symmetric, transitive and consistent, and x.equals(null) must be false.
  • Overriding only equals: equal objects land in different buckets, so set.contains(copy) is false, map.get(copy) is null, and a HashSet can hold duplicates.
  • Use the same fields in both methods (Objects.equals, Objects.hash), or use a record, which writes both from all its components.
  • Fields used in hashCode must not change while the object is in a hash collection. A changed field leaves the entry in the old bucket: contains is false, a second add succeeds, and remove cannot find the old entry.
  • Same problem for HashMap keys. For TreeSet and TreeMap, changing a field used by compareTo breaks the tree order.
  • Safe fix: use fields that never change (a final id), make the class immutable, or remove the object before changing it.
  • JPA entities: the generated id is null before save, so equals on the id alone breaks sets of new entities. Use a business key, or compare ids only when both are not null. getClass() keeps symmetry when subclasses add fields. instanceof works with Hibernate proxies but can break symmetry.

The red pen

Common traps: mistake → fix

  • Mistake: Different hash codes are fine when equals is true

    Fix: equal objects must have equal hash codes.

  • Mistake: Same hash code means equal

    Fix: it is only a collision; equals decides.

  • Mistake: A key is safe to edit after it is in a HashMap

    Fix: editing a key field makes the entry unreachable.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the contract between equals and hashCode?
  2. What goes wrong if you override only equals?
  3. What does this Customer code print after setPhone is called on an object already in a HashSet?
  4. Which fields would you use in equals for an entity whose id comes from the database?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview