1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/* Create List containing n Copies of Specified Object Example This java example shows how to create a list consisting n copies of specified copies using nCopies method of Collections class. */ import java.util.Collections; import java.util.List; import java.util.Iterator; public class CreateListOfNCopiesExample { public static void main(String[] args) { /* To create a List containing n copies of specified Object use, static List nCopies(int n, Object obj) method of Java Collections class. This method returns immutable List containing n copies of the specified Object. */ List list = Collections.nCopies(5,"A"); //iterate through newly created list System.out.println("List contains, "); Iterator itr = list.iterator(); while(itr.hasNext()) System.out.println(itr.next()); } } /* Output would be List contains, A A A A A */ |
In Line 27, the method iterator(), is undefined for the type List.