VOOZH about

URL: https://www.geeksforgeeks.org/java/collections-ncopies-method-in-java/

⇱ Collections.nCopies() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections.nCopies() Method in Java

Last Updated : 6 May, 2025

The Collections.nCopies() method in Java is used to create an immutable list which contains multiple copies of the same object. This method is helpful if we want to initialize 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. This method is defined in the java.util.Collections class.

Syntax of Collections.nCopies() Method

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

Parameters:

  • n: The number of copies we want in the list.
  • object: The object that should be repeated.
  • T: The type of object.

Returns: It returns an immutable list with n references to the same object.

Important Points:

  • We cannot modify the returned list, because it is immutable.
  • If n is less than 0, it throws an IllegalArgumentException.
  • This method is useful for creating pre-filled data structures.

Examples of Collections.nCopies() Method

Example 1: Creating a list with 4 identical strings


Output
The list returned is:
GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks 

Explanation: This example creates a list with 4 references to the string "GeeksforGeeks" and prints each one.


Example 2: Another list with 3 identical elements


Output
The list returned is:
GeeksQuiz GeeksQuiz GeeksQuiz 

Explanation: In this example, the method returns a new list with 3 copis of "GeeksQuiz" also demonstrating another example of how to initialize lists with duplicate values.


Example 3: Using Collections.nCopies() with custom objects


Output
Book List:
Java Basics
Java Basics
Java Basics
Java Basics
Java Basics

This method is helpful where we need to work with a fixed number of repeated elements in a list without manually adding them each time.

Comment
Article Tags: