Saturday, September 6, 2025
HomeLanguagesJavaCollections.nCopies() in Java

Collections.nCopies() in Java

The role of Collections.nCopies() is to return an immutable list which contains n copies of given object. This function helps if we want to create a list with n copies of given object. The newly allocated data object is tiny i.e, it contains a single reference to the data object.

Syntax :

public static <T> List<T> nCopies(int number, T object)

where, number is the number of copies
of object and object represents the 
element which will appear number times
in the returned list. T represents generic type. 

Exception : The function throws IllegalArgumentException if value of number is less than 0.

Example :

Java




// Java code to show implementation
// of Collections.nCopies()
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating a list where first argument
        // represents the number of copies and
        // the second argument represents the
        // element to be copied for 'number' times
        // This will create 4 copies of the objects.
        List list = Collections.nCopies(4, "Lazyroar");
  
        // Displaying the list returned
        System.out.println("The list returned is :");
        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
        System.out.println("\n");
  
        List list1 = Collections.nCopies(3, "GeeksQuiz");
      
        // Displaying the list returned
        System.out.println("The list returned is :");
        Iterator itr1 = list1.iterator();  
        while (itr1.hasNext()) {
            System.out.print(itr1.next() + " ");
        }
        System.out.print("\n");
    }
}


Output :

The list returned is :
Lazyroar Lazyroar Lazyroar Lazyroar 

The list returned is :
GeeksQuiz GeeksQuiz GeeksQuiz  
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11805 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6754 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS