Course contentsShow
← Java
Lesson 1090 of 2,87025. Set ImplementationsFree lesson

Modifying Objects After Adding to HashSet

Discover why changing an object's hash code fields after insertion makes it 'lost' in the Set.

Modifying Objects After Adding to HashSet

What you'll learn: Why changing an object's hash code fields after inserting it into a HashSet makes the object effectively "lost" in the Set.

The Disappearing Object Problem

When you add an object to a HashSet, the Set calculates the object's hash code to determine which internal bucket to store it in. This hash code is based on the object's state at that moment. If you later modify the fields that hashCode() uses, the object's hash code changes—but the object remains in the old bucket.

Now the HashSet is broken: when you try to find or remove the object, HashSet calculates the new hash code and looks in the wrong bucket. The object is technically still in the Set, but HashSet can't find it anymore.

Why This Happens

Think of a library where books are shelved by their first letter. You file "Moby Dick" under 'M'. If someone later changes the title to "The Whale" but doesn't move the book, you'll never find it by looking under 'T'. The book is lost because its location no longer matches its identifier.

HashSet works the same way: the bucket location is determined when you add the object. Changing the object's hashCode-relevant fields afterward creates a mismatch between where the object is stored and where HashSet looks for it.

The Cardinal Rule

Never modify any field that hashCode() depends on after adding an object to a HashSet (or any hash-based collection). If you must modify objects, either:

  • Remove the object before modifying it, then re-add it
  • Only use immutable fields in your hashCode() implementation
  • Avoid putting mutable objects in hash-based collections

Key Takeaway: Modifying an object's hash code fields after insertion into a HashSet breaks the collection's internal structure, making the object "lost" and unretrievable even though it technically remains in the Set.