-2

So I am trying to shuffle the same ArrayList (knots) 50 times in a for-loop and adding the shuffled list to another ArrayList (gen0). But every time I add a new ArrayList it overwrites all existing ArrayList-elements to the same ArrayList I just added, can someone tell me why?

ArrayList<ArrayList> seed(ArrayList<PVector> knots) {

  ArrayList<ArrayList> gen0 = new ArrayList<ArrayList>();
  for(int i=1; i<=50; i++) {

    Collections.shuffle(knots);

    gen0.add(knots);    
  }

  return gen0;
}```
Theodor Peifer
  • 3,097
  • 4
  • 17
  • 30

1 Answers1

0

You are shuffling the reference to the same ArrayList every time. Instead, consider copying the ArrayList on each iteration

ArrayList<PVector> newList = new ArrayList<>(knots); // creates a copy
Collections.shuffle(newList);
gen0.add(newList);
Earthcomputer
  • 96
  • 1
  • 4