javacollectionsimmutability

Java Immutable Collections


From Java 1.6 Collection Framework documentation:

Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable. [...] Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

The second criteria confuses me a bit. Given the first collection is unmodifiable, and assuming that the original collection reference has been disposed away, what are the changes that are referred to in the second line? Is it referring to the changes in the elements held in the collection ie the state of the elements?

Second question:
For a collection to be immutable, how does one go about providing the additional guarantees specified? If the state of an element in the collection is updated by a thread, is it sufficient for immutability that those updates in the state are not visible on the thread holding the immutable collection?


Solution

  • Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.

    Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.

    Here's a quote from guava's ImmutableList

    Unlike Collections.unmodifiableList(java.util.List<? extends T>), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.

    So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.