Collections

Create List of n copies of an Object example

This is an example of how to create a List of n copies of an Object. We will use the nCopies(int n, T o) API method of Collections. Creating a List of n copies of an Object implies that you should:

  • Invoke the nCopies(int n, T o) API method of Collections. It returns an immutable List containing n copies of the specified Object. Its parameters are the number of elements in the returned list and the element to appear repeatedly in the returned list. In the example we use 5 copies of the String “element”.
  • Use an Iterator over the list to get all elements of the list.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.Collections;
import java.util.List;
import java.util.Iterator;
 
public class CreateListOfNCopies {
 
  public static void main(String[] args) {
 
    // static List nCopies(int n, Object obj) method returns immutable List containing n copies of the specified Object
    List list = Collections.nCopies(5,"element");
 
    System.out.println("List elements : ");
    Iterator it = list.iterator();
 
    while(it.hasNext())

System.out.println(it.next());
 
  }
}

Output:

List elements : 
element
element
element
element
element

 
This was an example of how to a List of n copies of an Object in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button