Beware the hashcode!

(With thanks to my colleague Armand "jojo" Dijamco)

What does this code print?

Map map = new HashMap();
Collection things = new HashSet();
things.addmap );
System.out.printlnthings.containsmap ) );
map.put"foo""bar" );
System.out.printlnthings.containsmap ) );

Be wary of storing mutable objects in a HashSet, or using them as keys in a HashMap. An implementation side effect of using a collection that relies on hash codes is that making changes to the object in a way that alters its hash code will cause it to no longer be considered the same object. There's no way (short of removing and re-adding the item from the collection) to inform a collection that a mutable object needs to be re-hashed.

Item 13 in Josh Bloch's Effective Java tells us to "Favor Immutability". He also tells us in item 8 to "Always override hashCode when you override equals". A corollary is that you should not use mutable objects as keys in HashMaps or values in HashSets. If such objects correctly implement hashCode, they're not reliable in hashcode-based collections.

AddThis Social Bookmark Button

No comments:

Post a Comment