Video in progress

Strong Middle ☕ Core Java

An object put into a HashMap can't be found later. What could be wrong in the key class?

Set<Order> set = new HashSet<>();
Order o = new Order("A-1");
set.add(o);
o.setNumber("A-2");          // hashCode is computed from this field
System.out.println(set.contains(o)); // ?

Most likely the key is mutable: the field that hashCode() is computed from changed after put. The object stays in the old bucket, while get looks in a different bucket using the new hash.

📖 Answer

The result is false. Worst of all, the object is still inside the set and size() returns 1, but you can neither find it nor remove it.

What happened:

  1. At add time, hashCode() was h1, and the object went into the h1 bucket.
  2. The field changed, and now hashCode() is h2.
  3. contains looks in the h2 bucket, and there's nothing there.

In practice this often shows up with JPA entities: hashCode() is based on id, the entity is added to a HashSet before persist (id == null), then Hibernate assigns the id, and the set "breaks".

To prevent it:

  • use an immutable object as the key (String, a record, an immutable class);
  • make hashCode() depend only on fields that never change (for example, a business key, or a UUID assigned at creation);
  • the common approach for entities: hashCode() returns a constant that depends on the class, and equals() compares by id.

The sign when debugging: map.size() is bigger than expected, but get returns null, or remove deletes nothing.