Java Utility Library

Java Collections - nCopies() Method



The java.util.Collections.nCopies() method returns an immutable list consisting of n copies of the specified object.

Syntax

public static <T> List<T> nCopies(int n, T o)

Here, T is the type of element to be copied and object in the list.


Parameters

n Specify the number of elements in the returned list.
o Specify the element to appear repeatedly in the returned list.

Return Value

Returns an immutable list consisting of n copies of the specified object.

Exception

Throws IllegalArgumentException, if n < 0.

Example:

In the example below, the java.util.Collections.nCopies() method is used to get a immutable list containing specified number of specified element.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a list object using ncopies methos
    List<Integer> MyList = Collections.nCopies(5, 25);

    //printing the list
    System.out.println("MyList contains: " + MyList); 
  }
}

The output of the above code will be:

MyList contains: [25, 25, 25, 25, 25]

❮ Java.util - Collections