gpt4 book ai didi

java - 为什么需要多次创建数组?

转载 作者:行者123 更新时间:2023-12-02 03:15:49 24 4
gpt4 key购买 nike

该程序成对地打乱源列表。所以原来的列表

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

转换为

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],您可以有效地为添加到列表中的每一对构建一个新的字符串数组,这正是您想要的。

关于java - 为什么需要多次创建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com