Course contentsShow
← Java
Lesson 1259 of 2,87028. Collections Utility ClassFree lesson

Collections.nCopies: Repeated Elements

Generate immutable lists containing n copies of the same element using nCopies factory method.

Collections.nCopies: Repeated Elements

What you'll learn: How to instantly create an immutable list containing multiple copies of the same element without writing loops or consuming much memory.

The Core Idea

Collections.nCopies(int n, T object) generates a fixed-size, immutable list that appears to contain n copies of the same element. The clever part? It doesn't actually store n separate references in memory—it uses a space-efficient implementation that stores only one reference and returns it n times. Think of it like a magic photocopier that doesn't need paper: it just shows you the same original document over and over.

How to Use nCopies

The method takes two parameters:

  • n: the number of copies you want
  • object: the element to repeat (can even be null)
import java.util.*;

List<String> fiveHellos = Collections.nCopies(5, "Hello");
System.out.println(fiveHellos); // [Hello, Hello, Hello, Hello, Hello]

List<Integer> tenZeros = Collections.nCopies(10, 0);
System.out.println(tenZeros.size()); // 10
System.out.println(tenZeros.get(7)); // 0

Common Use Cases

Initializing collections with default values:

List<String> defaults = new ArrayList<>(Collections.nCopies(100, "N/A"));
// Now you have a mutable list prefilled with 100 "N/A" strings

Quick testing or placeholder data:

List<Boolean> flags = Collections.nCopies(20, false);

Important Constraints

The returned list is immutable—you cannot add, remove, or change elements. It's a read-only view. If you need a modifiable version, wrap it in a new ArrayList as shown above.

Key Takeaway: Use Collections.nCopies(n, element) to efficiently create immutable lists with repeated elements—perfect for initialization, defaults, or testing scenarios where you need many copies of the same value.