0

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));
    }

3 Answers 3

9

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 });
}
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

2

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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.