Why won't it remove from the set?

java, puzzle

Solution

For a HashSet, this can occur if the object's hashCode changes after it has been added to the set. The HashSet.remove() method may then look in the wrong Hash bucket and fail to find it.

This probably wouldn't happen if you did iterator.remove(), but in any case, storing objects in a HashSet whose hashCode can change is an accident waiting to happen (as you've discovered).

Problem

This bug took me a while to find... Consider this method: ``` public void foo(Set<Object> set) { Object obj=set.iterator().next(); set.remove(obj) } ``` I invoke the method with a non-empty hash set, but no element will be removed! Why would that be?

Original source