pagetop
Javablog
by Java coders, for Java codersRSS

Mutable entries in a Collection

October 19th, 2008 by

It 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 a HashMap.

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.


This entry was posted by by on Sunday, October 19th, 2008 at 4:31 pm, and is filed under Collections, Concurrency, Immutable, Java, Mutable. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



2 comments on “Mutable entries in a Collection”

Actually it’s not threads that cause problems in these situations.


List<String> list = new ArrayList<String>();
Map<List<String>,String> map = new HashMap<List<String>,String>();
list.add("one");
map.put(list, "value");
list.add("two");

This is problematic by itself in a single-threaded environment. Now if you publish state, i.e. if you were to expose the list variable, then threads can bring additional havoc.

[…] Javablog by Java coders, for Java coders « Mutable entries in a Collection […]

Leave a comment

Markdown is supported.

To include code snippets in your comment, use

<pre><code># lang java
... code here ...
</code></pre>

or use 4 spaces at the start of the line instead of using code and pre tags.

Comment feed: RSS