Immutable List with nCopies()

Immutable List with nCopies()

The nCopies() method of Collections class returns an immutable object of List. The immutable object cannot be modified. It is read-only. If tried to modify, the JVM throws UnsupportedOperationException.

Following is the method signature

  • static List nCopies(int n1, Object obj1): Returns an immutable list containing n1 elements of the object obj1. That is add() method does not work.
Following program on Immutable List with nCopies() illustrates.

Immutable List with nCopies()
Output screenshot on Immutable List with nCopies()

List firstList = Collections.nCopies(3, 10);

The Collections.nCopies(3, 10) method returns an object of List, firstList, that contains three elements of same value 10. Observe the above screenshot.

// firstList.add(20);

As the returned object firstList() is immutable, the add() method does not work and throws UnsupportedOperationException at runtime.

ArrayList secondList = new ArrayList(Collections.nCopies(5, “hello”));
secondList.add(“sir”);
secondList.set(1, “world”);
secondList.add(3, “wihes”);

The above ArrayList object, secondList, constructor is created very differently. While creating itself, 5 elements of "hello" are added. The object secondList created in this way accepts overloaded add() method and set() method.

ArrayList thirdList = new ArrayList();
thirdList.add(100);
thirdList.addAll(Collections.nCopies(3, 1000));

In a general way, the thirdList object is created and added an element 100. After adding 100, with nCopies() method, three elements of 1000 are added.

Different styles of nCopies() method usage is shown and the programmer can adopt required style in coding.

One thought on “Immutable List with nCopies()

Leave a Reply

Your email address will not be published. Required fields are marked *