Java Programming Tutorials

Java programming tutorials with many code examples!

Java Collections nCopies


How to create a Java List with copies of the same element? Java Collections.nCopies(n, T) does that, but has its quirks. Read on…


One way to create a List consisting only of the same element is to use java.util.Collections.nCopies(n, T). The method creates an immutable List with n the same items.

The following example explains how nCopies(n, T) works:


import java.util.Collections;

public class CollectionsNCopies {

    static class MyObject {
        int x = 3;

    public static void main(String[] args) {
        MyObject o = new MyObject();
        System.out.println("object: " + o + " with x = " + o.x);

        nTimes(3, o);

        // changes all items in list:
        o.x = 42;
        nTimes(3, o);

    private static void nTimes(int i, MyObject proto) {
        for (MyObject mo : Collections.nCopies(i, proto)) {
            System.out.println(mo + " with x = " + mo.x);

Remember that returned List is immutable and cannot be changed. Also, nCopies(n, T) throws IllegalArgumentException when n < 0, but zero is allowed.

Running the above Java program gives the following:

object:$MyObject@677327b6 with x = 3
Result:$MyObject@677327b6 with x = 3$MyObject@677327b6 with x = 3$MyObject@677327b6 with x = 3
Result:$MyObject@677327b6 with x = 42$MyObject@677327b6 with x = 42$MyObject@677327b6 with x = 42

Note that all objects in returned lists refer to the same reference: 677327b6. So the element is never duplicated and changing any of them – changes all.

Was it helpful? Share!