HashSet Breakage: The Same Root Cause
What you'll learn: You'll discover that HashSet suffers the exact same breakage as HashMap when equals and hashCode are inconsistent—because HashSet secretly uses HashMap under the hood.
The Internal Reality of HashSet
Here's the critical insight: HashSet doesn't implement its own storage mechanism. Instead, it wraps a HashMap internally! When you add an element to a HashSet, Java stores it as a key in a hidden HashMap, with a dummy placeholder object as the value.
This means every behavior we've seen with broken HashMap operations applies identically to HashSet.
The Same Symptoms Appear
When your class violates the equals-hashCode contract:
- Duplicate elements appear: The set can contain what should be duplicates because different hash codes send "equal" objects to different buckets.
- Contains checks fail: You add an object, then immediately call
contains()with an equal object, and it returnsfalse. - Remove operations fail: Even though an element is logically present,
remove()can't find it.
Think of it this way: if HashSet is just a HashMap with keys only (no meaningful values), then breaking the key contract breaks the set the same way.
Why This Matters
You might think sets and maps are completely different data structures. But understanding this implementation detail explains why the same equals and hashCode bugs cause problems in both. Fix the contract once, and both collections work correctly.
Key Takeaway: HashSet uses HashMap internally, storing elements as keys—so the exact same equals-hashCode contract violations that break HashMap also break HashSet, causing duplicate elements and failed lookups.