List nCopies demo

In this post under Java Collections, I will explain with example the purpose of “nCopies” static method in “Collections” utility class

This method creates a list containing n copies of input object. Where n and input object are user specified.

So basically this method takes two arguments.
1) The object to be replicated in the list
2) How many times the object has to be replicated.

So if we want a list containing 5 copies of integer 1. Then the method call should be like below

List<Integer> list = Collections.nCopies(5, 1);

Where 5 is number of copies of input object and 1 is input object itself

In this way we can use “nCopies” static method of “Collections” utility class.

Below is the main class for your reference

Main class

package core.collection;

import java.util.Collections;
import java.util.List;

public class ListNCopiesDemo {
    public static void main(String[] args) {
        List<Integer> list = Collections.nCopies(5, 1);
        System.out.println(list.toString());
    }
}

Below is the output

Output

[1, 1, 1, 1, 1]

Leave a comment