Collections trivia – Unmodifiable Collections
Posted by tanvis on July 10, 2007
Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException.
Collection<T> unmodifiableCollection(Collection<? extends T> c)
List<T> unmodifiableList(List<? extends T> list)
Set<T> unmodifiableSet(Set<? extends T> s)
SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
import java.util.*;
public class Unmod{
public static void main(String[] args){
List<String> strlist = new ArrayList<String>();
strlist.add(“C”);
strlist.add(“B”);
strlist.add(“A”);
Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist);
// unmodstrlist.add(“G”); throws UnsupportedOperationException
Set<String> strset = new TreeSet<String>();
strset.add(“C”);
strset.add(“B”);
strset.add(“A”);
Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset);
// unmodstrset.add(“G”); throws UnsupportedOperationException
}
public static Collection<String> makeUnmodifiable(Collection<String> c){
return(Collections.unmodifiableCollection(c));
}
}