Mutable entries in a Collection
October 19th, 2008 by SamIt has been noted by many well respected developers such as Brian Goetz and Josh Bloch that
If an object’s
hashCode()value can change based on its state, then we must be careful when using such objects as keys in hash-based collections to ensure that we don’t allow their state to change when they are being used as hash keys. All hash-based collections assume that an object’s hash value does not change while it is in use as a key in the collection. If a key’s hash code were to change while it was in a collection, some unpredictable and confusing consequences could follow. This is usually not a problem in practice — it is not common practice to use a mutable object like a List as a key in aHashMap.
But it’s all too easy to instantiate a new HashSet every time you define a Collection, simply out of habit.
I bet if you were to go through your code and check all your uses of Collection or Set, you might find that many of them should be ArrayList in order to guard against changes in your entries after they’ve been added. You’re probably only getting away with it because your code is not being subjected to many threads that are acting on the entries. Be particularly mindful of field variables if they are not collections of immutable objects such as primitive wrappers and String.
Michael wrote:
November 1st, 2008 at 6:20 pm