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

Breaking HashSet with Bad hashCode

See how a broken hashCode causes HashSet to store duplicates and fail contains checks.

Breaking HashSet with Bad hashCode

You'll learn how a poorly implemented hashCode method can completely destroy HashSet's ability to prevent duplicates and find elements.

The Critical Role of hashCode

Remember that HashSet uses hashCode() to decide which bucket to place an object in. When you override equals() but fail to properly override hashCode(), you violate the equals-hashCode contract: equal objects must return the same hash code.

What Happens When hashCode Is Broken

Imagine a filing cabinet where two identical documents are supposed to have the same label, but you accidentally give them different labels. You'll file them in different drawers, and when you search for one, you'll only check one drawer—missing the duplicate in the other.

When two objects are equals() but have different hash codes, HashSet:

  1. Stores duplicates: The second "equal" object goes into a different bucket, so HashSet doesn't detect it's a duplicate during add()
  2. Fails contains() checks: Searching for an object looks in the wrong bucket because the hash code doesn't match what was used during insertion
  3. Breaks the fundamental Set contract: You end up with multiple "equal" objects in the same set

The Disaster in Practice

If your Person class returns a random number from hashCode(), or always returns a constant while using meaningful field comparisons in equals(), HashSet becomes unreliable. Elements that should be found go missing. Duplicates appear where there should be none.

Key Takeaway: A broken hashCode() turns HashSet from a reliable data structure into an unpredictable mess—duplicates slip through, and valid elements vanish from searches. The equals-hashCode contract isn't optional; it's mandatory for correct HashSet behavior.