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<String> mutable = new ArrayList<>(Collections.nCopies(10, "Hi"));
As the JavaDoc says, the returned list is immutable, which means you can't modify it:
[nCopies] Returns an immutable list consisting of n copies of the specified object.
Maybe you didn't get the "in combination with the List.addAll" part. You must have a non-immutable list in which you can add all your elements:
List modifiableList = new ArrayList<String>();
List<String> hi = Collections.nCopies(10, "Hi");
List<String> are = Collections.nCopies(10, "Are");
modifiableList.addAll(are);
modifiableList.addAll(hi);
modifiableList.forEach(System.out::println);