Problem:
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…
Solution:
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:
package com.farenda.java; 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) { System.out.println("Result:"); 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: com.farenda.java.CollectionsNCopies$MyObject@677327b6 with x = 3 Result: com.farenda.java.CollectionsNCopies$MyObject@677327b6 with x = 3 com.farenda.java.CollectionsNCopies$MyObject@677327b6 with x = 3 com.farenda.java.CollectionsNCopies$MyObject@677327b6 with x = 3 Result: com.farenda.java.CollectionsNCopies$MyObject@677327b6 with x = 42 com.farenda.java.CollectionsNCopies$MyObject@677327b6 with x = 42 com.farenda.java.CollectionsNCopies$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.