gpt4 book ai didi

Java List 未正确填充

转载 作者:行者123 更新时间:2023-12-01 07:48:54 27 4
gpt4 key购买 nike

我写下了以下代码。

    ArrayList<int []> l = new ArrayList<>();
int [] temp = new int[2];
int n=1;
for(int i=0;i<10;i++)
{
for(int j=0;j<2;j++)
{
temp[j]=n++;
}
l.add(temp);
}

for(int i=0;i<10;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(l.get(i)[j] + " ");
}
System.out.println();
}

输出:

 19 20 
19 20
19 20
.
.
19 20

我不明白为什么输出是这样的。我正在使用每次都会更改的临时数组填充列表。我做错了什么?

最佳答案

您正在使用对同一数组对象的多个引用来填充List。您必须在向 List 添加元素的循环的每次迭代中创建一个新数组。

for (int i = 0; i < 10; i++) {
int [] temp = new int[2];
for (int j = 0; j < temp.length; j++) {
temp[j] = n++;
}
l.add(temp);
}

关于Java List<int []> 未正确填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920924/

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