MurphyApps
MurphyApps

Reputation: 13

Java ArrayList populating

So I am creating an method that shuffles a group of numbers and the idea is that i create a population of these numbers. So I create a loop which shuffles the numbers and then adds it to an arraylist, however after a few debugging statements I found that it does shuffle the numbers but only adds the last shuffle to the arrayList. Can anyone help me figure out why?

solutionList is an arraylist further up the code if anyone was wondering

for(int k =0;k <100; k++){
        Collections.shuffle(solutionList);
        population2.add(new Object[]{solutionList}) ;
        System.out.println("In the loop  " + solutionList);

    }

    for(Object[] row : population2){
        System.out.println("Row = " + Arrays.toString(row));
    }

Upvotes: 0

Views: 616

Answers (3)

JB Nizet
JB Nizet

Reputation: 691865

You're creating 100 arrays, each containing a reference to the same list. I think what you want is creating 100 arrays, each containing a copy of the elements of the list:

for(int k =0;k <100; k++){
    Collections.shuffle(solutionList);
    population2.add(solutionList.toArray()) ;
}

But I would advise avoiding arrays completely, and always using collections:

for(int k =0;k <100; k++){
    Collections.shuffle(solutionList);
    population2.add(new ArrayList<Something>(solutionList));
}

Upvotes: 2

Jochen
Jochen

Reputation: 2295

population2.add(new Object[]{solutionList}) ;

creates an Object array with a single element. That element happens to be a list.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1501596

Each element of population2 is an array with a reference to the same ArrayList. If you want different lists, you need to create a new one for each iteration.

For example, to avoid populating the list with the right numbers each time, you could just shuffle solutionList and then add a reference to a copy:

for (int k = 0; k < 100; k++) {
    Collections.shuffle(solutionList);
    List<Integer> copy = new ArrayList<Integer>(solutionList);
    population2.add(new Object[]{ copy });
}

Upvotes: 9

Related Questions