How can I create a read only Collection?

Brandon Rohlfs

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));
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact