Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
copy
communitycreator

What is Collections.nCopies in Java?

abhilash

The nCopies function in the Collections class is used to make copies of a given object. Collections is defined in the util package in Java, so you must import the util package before you can use the nCopies function, as shown below.

import java.util.Collections;

The syntax for the nCopies function is shown below.

Collections.nCopies(list, object)

Method signature

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

Parameters

  • int n: the number of elements in the returned list.
  • T o: the element to appear repeatedly in the returned list.

Parameter types

<T>: the class of the object to copy and of the objects in the returned list.

Note: To learn more about parameter types, click here.

Return value

The return value is an immutable list that consists of n copies of the specified object.

Code

The example below will help you understand the nCopies function better. We first define the object to be copied and the number of times it has to be copied. Then we use the nCopies function to copy the object the specified number of times.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        String stringToBeCopied = "educative";
        int copyCount = 5;
        List<String> list = Collections.nCopies(copyCount, stringToBeCopied);

        System.out.println("The list returned is: " + list);

    }
}

RELATED TAGS

java
copy
communitycreator
RELATED COURSES

View all Courses

Keep Exploring