Why does Collections.shuffle() fail for my array?

前端 未结 4 1240
萌比男神i
萌比男神i 2020-12-05 10:42

Why does my code not work?

package generatingInitialPopulation;

import java.util.Arrays;
import java.util.Collections;

public class TestShuffle {
    publi         


        
4条回答
  •  广开言路
    2020-12-05 11:12

    Try adding this line of code to your test:

    List l=Arrays.asList(arr);
    System.out.println(l);
    

    You will see you are printing out a single element List.

    Using Arrays.asList on a primitive array cause asList to treat the int[] as a single object rather than an array. It returns a List instead of a List. So, you are basically shuffling a single element List and so nothing really gets shuffled.

    Notice that some of the answers already given are wrong because asList returns a List backed by the original array, nothing gets copied - all changes are reflected in the orginal array.

提交回复
热议问题