How can I create an immutable List consisting of n Copies of an Object?

Brandon Rohlfs

nCopies(int n, T o) can be used to create an immutable List which contains a specific number of copies of an Object. Care must be taken when trying to add elements to or extract elements from the returned List. Both attempts will throw UnsupportedOperationExceptions.

public static <T> List<T> nCopies(int n, T o)
import java.util.List; 
import java.util.Collections; 

public class NCopiesTest{
 public static void main(String[] args){
  List<String> slist = Collections.nCopies(5, "Java Blend"); //immutable list!
  slist.add("Moca Blend"); // throws UnsupportedOperationException!
  String selement = slist.remove(0); // throws UnsupportedOperationException!
 }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


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

 

 

About | Sitemap | Contact