how do you change the order in collections to not modify all the arrays of a list?

nCopies doesn’t create copies of the element you pass to it, so q contains a List where the same ArrayList<String> instance is repeated x times. When you shuffle one of them, you shuffle all of them (since there is actually only one of them).

To create a List of x distinct copies, you can use Streams:

List<ArrayList<String>> q = 
    IntStream.range(0,x)
             .mapToObj(i -> new ArrayList<String>(slotType.getSlotitems()))
             .collect(Collectors.toList());

Now shuffle would only affect one of the ArrayLists.

Another option:

  List<ArrayList<String>> q =
      Collections.nCopies(x,slotType.getSlotitems())
                 .stream()
                 .map(ArrayList::new)
                 .collect(Collectors.toList());

Here I took your original List<ArrayList<String>> (where all the elements are the same instance) and created a new List<ArrayList<String>> where each element is a copy of the original element.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top