【问题标题】:Java using Lists to store ListsJava使用Lists来存储Lists
【发布时间】:2013-11-30 12:42:43
【问题描述】:

我尝试创建一个包含 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); 更改为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次! 你知道是什么原因吗?

【问题讨论】:

    标签: java list for-loop store


    【解决方案1】:

    因为您在每次迭代时将整数添加到相同 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++;
    }
    

    【讨论】:

      【解决方案2】:

      这些列表很可能引用了相同的 List 对象。为避免这种情况,您需要在每次迭代时添加一个new List&lt;Integer&gt;

      你可以这样做

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

      【讨论】:

        【解决方案3】:

        列表很可能引用了同一个List对象,在将list1添加到list2之后,您更改了list1。所以list2中的list1也发生了变化。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多