Create a List containing n Copies of Specified Object
Create a List containing n Copies of Specified Object This java example shows how to create a list consisting n copies of specified copies using nCopies method of Collections class.
To create a List containing n copies of specified Object use static List nCopies(int n, Object obj) method of Java Collection class.This method returns immutable List containing n copies of the specified Object.
The Output of above program:
Reference Books:
To create a List containing n copies of specified Object use static List nCopies(int n, Object obj) method of Java Collection class.This method returns immutable List containing n copies of the specified Object.
import java.util.Collections; import java.util.List; import java.util.Iterator; public class CreateListOfNCopiesExample { public static void main(String[] args) { 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()); } }
The Output of above program:
List contains, A A A A A
Reference Books: