此程序按对随机排列源列表。这样原来的清单


  “ 1”,“ 2”,“ 3”,“ 4”,“ 5”,“ 6”,“ 7”,“ 8”,“ 9”,“ 10”,“ 11”,“ 12”,“ 13” “,” 14“,” 15“,” 16“,” 17“,” 18“,” 19“,” 20“


trasfoms至


  11 ^ 12 19 ^ 20 17 ^ 18 15 ^ 16 1 ^ 2 5 ^ 6 3 ^ 4 13 ^ 14 7 ^ 8 9 ^ 10


注释行未注释时,以上内容是正确的。现在,如果注释A行,那么shuffleList中的所有元素都是19^20

public class ShuffleService {

public static void shuffleList(List<String> list) {

    System.out.println(list);

    ArrayList<String[]> shuffleList = new ArrayList<String[]>(10);
    String[] arr = new String[2];
    boolean flag = false;
    int step = 0;

    for(String s: list){

        if(flag){
            arr[1]=s;
        } else {
            arr[0]=s;
        }

        flag=!flag;
        step++;

        if(step==2){
            shuffleList.add(arr);
            step=0;
            //arr = new String[2]; //**line A**
        }
    }

    Collections.shuffle(shuffleList);

    for(String[] val: shuffleList){
        System.out.print(val[0]);
        System.out.print("^");
        System.out.println(val[1]);
    }


}

public static void main(String[] args) {
        String[] a = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"};
        List<String> list1 = Arrays.asList(a);
        shuffleList(list1);
    }
}


那么,为什么我需要取消注释程序中的A行才能正常工作?

最佳答案

因为当您将值重写为arr(而无需重新生成)时,您还将修改列表中已有的值。

将对象添加到列表并不会阻止您对其进行修改,它不会自己复制。通过在循环中调用new String[2],可以有效地为添加到列表中的每一对创建一个新的字符串数组。

07-26 09:26
查看更多