Saturday, December 13, 2025
HomeLanguagesJavaCreate List containing n Copies of Specified Object in Java

Create List containing n Copies of Specified Object in Java

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.

Example:

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

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

Declaration:

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

Java




// Create List containing n Copies
// of Specified Object in java
import java.io.*;
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);
  
        System.out.println(myList);
    }
}


Output

[GFG, GFG, GFG, GFG, GFG]
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32447 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6815 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12031 POSTS0 COMMENTS
Shaida Kate Naidoo
6951 POSTS0 COMMENTS
Ted Musemwa
7202 POSTS0 COMMENTS
Thapelo Manthata
6898 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS