为什么我需要多次创建一个数组?

时间:2016-10-30 15:24:27

标签: java

此程序按对象清洗源列表。那个原始列表

  

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

trasfoms to

  

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行才能正常工作?

1 个答案:

答案 0 :(得分:2)

因为当您将值重写为arr(不重新制作)时,您还将修改列表中已有的值。

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