DJUTILS - Delft Java Utilities  

Immutable collections

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 relationImmutable protectionOverhead
Omni-directional (all holders of the immutable collection see a snapshot of the collection that can never be altered)COPYLarge
One-directional (holders of the immutable collection see a collection that can be changed, though not by themselves)WRAPSmall

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 collectionConstructed fromCOPY / WRAP
ImmutableHashSet<E>Collection<E>Implicit COPY (into a HashSet)
Set<E>COPY (into a HashSet), or WRAP
ImmutableLinkedHashSet<E>Collection<E>Implicit COPY (into a LinkedHashSet)
Set<E>COPY (into a LinkedHashSet), or WRAP
ImmutableArrayList<E>Collection<E>Implicit COPY (into an ArrayList)
List<E>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.