[英]Java using Lists to store Lists
我试图用2个列表创建一个程序; list1( List<Integer>
),它将不断添加新值,list2( List<List<Integer>>
)将存储list1的值。 我从这开始:
int x=1;
while(x<=10)
{
list1.add(x);
System.out.println(list1);
x++;
}
输出就像我想的那样;
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
然后我改变了System.out.println(list1);
to list2.add(list1);
然后包括一个增强的for循环;
for(List<Integer> y:list2)
{
System.out.println(y);
}
但它不是像以前那样输出,而是说:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
就像它只重复list1的最后状态10次! 你知道吗,原因是什么?
列表很可能引用相同的List
对象。 为避免这种情况,您希望每次迭代添加一个new List<Integer>
。
你可以这样做
int x = 1;
while (x <= 10) {
int y = 1;
while (y <= x) {
List<Integer> list = new List<Integer>();
list.add(y);
y++;
}
y = 1;
list2.add(list);
}
for (List<Integer> list: list2){
System.out.println(list);
}
因为在每次迭代时将整数添加到同一个 List
对象,然后将此列表对象添加到列表对象列表中。
想想这样的情况:
一种解决方法可能是:
int x=1;
while(x <= 10){
l1 = new ArrayList<>(l1);//create a new list object with values of the old one
l1.add(x);
l2.add(l1);
x++;
}
列表很可能引用相同的List对象,在将list1添加到list2之后,您更改了list1.so list2中的list1也已更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.