This package augments the Java collections framework with immutable variants.
When a collection is shared between different parties (classes or packages) there is often an implied trust that none of the parties subsequently modifies that collection. Violating such trust may break applications in ways that are very hard to debug. One commonly used way to deal with passing collections among untrusting parties is to pass around only copies of those collections instead of the collections themselves. Obviously, this may be expensive, both in memory requirements and in cpu time. This immutable collections package makes these (expensive) copies only when none of the parties may modify the collection. The immutable collections package also implements a one-way trust relation by providing an immutability shield around a collection whose content can still be modified by holders of the original (embedded, wrapped) collection, but not by holders of the immutable collection. In this case the holders of the immutable collection should be aware that the collection may be modified by another party, but the overhead of making and storing a copy just to be safe from programming errors is avoided.
|Trust relation||Immutable protection||Overhead|
|Omni-directional (all holders of the immutable collection see a snapshot of the collection that can never be altered)||COPY||Large|
|One-directional (holders of the immutable collection see a collection that can be changed, though not by themselves)||WRAP||Small|
The classes in the immutable collections package embed the provided collection or a copy thereof (created at time of construction). The classes implement only those methods of the embedded collection that cannot modify it. The immutable collections can construct an Iterator, however the returned object is an ImmutableIterator that will throw an Exception if the remove method is called.
An immutable collection embedding a particular collection has the same generic parameters as the embedded collection. The constructors take a compatible collection object and then embed (wrap) that object, or a make and embed a copy of that collection object:
|Immutable collection||Constructed from||COPY / WRAP|
||Implicit COPY (into a HashSet)|
||COPY (into a HashSet), or WRAP|
||Implicit COPY (into a LinkedHashSet)|
||COPY (into a LinkedHashSet), or WRAP|
||Implicit COPY (into an ArrayList)|
||COPY (into an ArrayList), or WRAP|
|ImmutableHashMap<K,V>||Map<K,V>||COPY (into a HashMap), or WRAP|
The immutable collection package does not provide any protection against modifications of the objects contained in those collections. Whether the contents of immutable collections are prone to change is a property of those objects.