Collections.nCopies: Creating Immutable Repeated Lists
What you'll learn: How to instantly generate an immutable list filled with repeated copies of the same element using Collections.nCopies.
What Is Collections.nCopies?
Collections.nCopies is a static factory method that creates a lightweight, immutable list containing n copies of a specified element. Think of it like ordering 100 identical printed flyers—you get many copies, but they all reference the same original content.
The magic here is efficiency: instead of creating 1,000 separate objects, Java creates a single smart wrapper that pretends to hold 1,000 elements while actually storing just one reference.
How It Works
List<String> repeatedList = Collections.nCopies(5, "Hello");
System.out.println(repeatedList);
// Output: [Hello, Hello, Hello, Hello, Hello]
System.out.println(repeatedList.size()); // 5
System.out.println(repeatedList.get(2)); // "Hello"
The list behaves like a normal list for reading operations—you can call get, size, iterate through it—but you cannot modify it. Any attempt to add, remove, or replace elements throws an UnsupportedOperationException.
Common Use Cases
Initialization and padding:
// Create a list pre-filled with default values
List<Integer> defaults = new ArrayList<>(Collections.nCopies(10, 0));
// Now you have a mutable list: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
// Pad a string list with empty strings
List<String> padded = new ArrayList<>();
padded.addAll(Collections.nCopies(5, ""));
Bulk operations:
// Add the same value multiple times
myList.addAll(Collections.nCopies(100, "placeholder"));
Memory and Performance
Because all elements reference the same object, this method is extremely memory-efficient and instantaneous—even for millions of copies.
Key Takeaway: Collections.nCopies(n, element) creates a space-efficient, immutable list with n repetitions of element, perfect for initialization, padding, and bulk operations where you need many copies of the same value.