Java使用列表(Lists)来存储列表(Lists)。

4

我尝试创建一个程序,其中包含两个列表: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);改为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次!你知道原因吗?

3个回答

4

这些列表很可能引用了同一个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);
}

4

因为你在每次迭代中将整数添加到相同List对象中,然后将这个列表对象添加到你的列表的列表对象中。

可以想象一个这样的情况:

enter image description here 一个解决方法是:

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++;
}

0

这些列表很可能引用同一个列表对象,在将list1添加到list2之后,您更改了list1。因此,list2中的list1也发生了更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接