List hi = Collections.nCopies(10, \"Hi\");
List are = Collections.nCopies(10, \"Are\");
hi.addAll(are);
hi.forEach(System.out::println)
Collections.nCopies
returns an immutable List
, so you can't add anything to it:
Returns an immutable list consisting of n copies of the specified object.
It returns an immutable List
since it only contains a single reference of the element you pass to its constructor:
The newly allocated data object is tiny (it contains a single reference to the data object).
This is done for the benefit of performance and storage requirements - Collections.nCopies(10, "Hi")
and Collections.nCopies(10000000, "Hi")
occupy the same amount of space.
Therefore it would be very difficult to implement it as a mutable List. How would you set, for example, the 10000
'th element to some new value if there's no storage allocated for that element?
If you need a mutable List that contains copies of the same object, you have to pass the immutable List to some mutable List constructor:
List mutable = new ArrayList<>(Collections.nCopies(10, "Hi"));