Video in progress

Strong Middle 🧱 OOP and SOLID

If an object is modified after being added to a `HashSet`, what does this code print?

class Ticket {
    String seat;
    Ticket(String seat) { this.seat = seat; }
    @Override public boolean equals(Object o) {
        return o instanceof Ticket t && t.seat.equals(seat);
    }
    @Override public int hashCode() { return seat.hashCode(); }
}

Set<Ticket> sold = new HashSet<>();
Ticket t = new Ticket("A1");
sold.add(t);
t.seat = "B7";
System.out.println(sold.contains(t));
sold.remove(t);
System.out.println(sold.size());

It prints false and 1. After the object was added to the HashSet, a field used in hashCode changed, so it is now looked up in a different bucket and not found, yet it stays in the set.

📖 Answer

HashSet puts the object into a bucket by the hashCode at the moment it is added, and stores the hash. After that:

  • t.seat = "B7": the hash changed, but the set doesn't know;
  • contains(t): it looks in a different bucket by the new hash, and there is nothing there: false;
  • remove(t): for the same reason, it removes nothing;
  • size(): 1. The object is left "hanging" in the set. If you iterate, you will see it, but you can neither find it nor remove it.

In prod it shows up like this: a cache or Map slowly grows (a memory leak), duplicates appear, and you get bugs like "I added it but I can't find it".

This is an encapsulation and immutability problem:

  • fields used in equals/hashCode should be final;
  • best of all, make key objects immutable: record Ticket(String seat);
  • with JPA entities: don't build hashCode from fields that change. If it is based on the ID, the ID appearing after persist also changes the hash, which is why a constant like getClass().hashCode() or a natural key is often used.

If you must change it anyway: first remove it from the set, change it, then add it back.