Thursday, March 31, 2011

Creating read-only or unmodifiable collection in java

You can create a java collection which cannot be modified. These collections can be called read only collections or unmodifiable collections.

When we try to edit these read only collection we get UnsupportedOperationException.


Eg.
Read-only map can be obtained from unmodifiableMap function of collections:
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"apple");
map.put(2,"orange");
map.put(3,"banana");

// Create unmodifiable view
Map<Integer, String> readonlyMap = Collections.unmodifiableMap(map);

// This throws UnsupportedOperationException
readonlyMap.put(4,"clementine");

Methods by Collections class

The Collections class provides six factory methods, one for each of Collection, List, Map, Set, SortedMap, and SortedSet.

Collection unmodifiableCollection(Collection collection)
List unmodifiableList(List list)
Map unmodifiableMap(Map map)
Set unmodifiableSet(Set set)
SortedMap unmodifiableSortedMap(SortedMap map)
SortedSet unmodifiableSortedSet(SortedSet set)

You should set the collection with required values then pass it as value to the Collections’ respective method. Most important thing here is, just passing and setting it as unModifiableX is not enough. These methods will return you collection as read only. You need to overwrite your old collection with this new read only collection. If you don’t do that, using the reference of the old collection the values can be modified. Cool right!

The returned set will be serializable if the specified set is serializable. As mentioned earlier, if you attempt to modify a read-only collection it will throw an UnsupportedOperationException.


No comments:

Post a Comment

Chitika