Thursday, September 08, 2005

Immutable Collections in Java

Quite often, we may feel the need for an immutable collection, i.e. users cannot modify the collection and bring it to an invalid state, but can only read it.
The Collection API has methods to help us with this. For e.g. to get an immutable list, use the following code:

List ul = Collections.unmodifiableList(list);

Check out the other methods of Collections which give you other helper methods to make collections immutable. Any attempt to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

The 'immutablity' aspect can also be used as a design pattern for concurrent read-and-write access to a collection. (Think mutiple users or threads). Anyone who needs to modify a collection will make a copy of the collection object and modify it.