Skip to content
Related Articles

Related Articles

Improve Article

Create List containing n Copies of Specified Object in Java

  • Last Updated : 22 Dec, 2020
Geek Week

To create a Java List containing n Copies of a specified Object, nCopies() method of java.util.Collections class can be used. The nCopies() method takes two parameters – n the length of the list and the object which has to be copied n times in the list.


Input : n = 4, Object = "Hello"
Output: listOfObjects = ["Hello", "Hello", "Hello", "Hello"]

Input : n = 3, Object = 3
Output: listOfObjects = [3, 3, 3]


public static nCopies(int length, Object object)

Return Value: An immutable List containing n copies of the specified object.

Exception Throws: IllegalArgumentException
if the length provided is less than 0
i.e, n < 0


// Create List containing n Copies
// of Specified Object in java
import java.util.Collections;
import java.util.List;
class GFG {
    public static void main(String[] args)
        int n = 5;
        Object myObj = "GFG";
        List myList = Collections.nCopies(n, myObj);

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :