Google search bar

August 25, 2009

Java HashSet can "lose" objects

If the hash of an Object changes, the Object is 'lost' in a HashSet.

I have some code that invoked HashSet.remove(Object) and the object was NOT removed. Turned out that after the object was added to the set, a field that is involved in computing the HashSet was changed. Then, because the hash of the object changed, the remove method didn't remove the object. I tested in Sun Java 1.6.0_13 and in on IBM jdk 1.5. I found this blog post about the subject that contains a good explanation.

I don't think this limitation is sufficiently documented Java's HashSet.

Thanks to Boris Kirzner

http://boriskirzner.wordpress.com/2006/10/01/hashsetcontains-does-your-busket-contain-something/