【问题标题】:Adding elements from a List to a List of Lists将列表中的元素添加到列表列表
【发布时间】:2014-04-27 13:12:01
【问题描述】:

我尝试用 Java 编写一些代码 - 我有两个列表:

List<List<Integer>> listOfLists;
List<Integer> listOfIntegers;

我想将listOfIntegers 中的每个Integers 添加到listOfLists 中的新元素(List),然后我需要清除listOfIntegers

我试过了:

listOfLists.add(listOfIntegers);
listOfIntegers.clear();

但这会清除listOfLists 中对List 的引用

感谢曼努埃尔席尔瓦,我想出了我需要的东西:

List<Integer> newList = new ArrayList<>();
for (Integer i : lineIntegersList)
{
    newList.add(i);
}

listOfLists.add(newList);                   
lineIntegersList.clear();

【问题讨论】:

  • 为什么需要列表列表?
  • 如果您刚才发布的代码是您正在寻找的代码,那么您不需要编写自己的for 循环。只需使用像 List&lt;Integer&gt; newList = new ArrayList&lt;&gt;(lineIntegersList); 这样的 copping 构造函数。

标签: java list integer


【解决方案1】:

你可以做这样的事情......

 ArrayList<ArrayList<String>> listOlists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOlists.add(singleList);

ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOlists.add(anotherList);

感谢@tster - 在这里您实例化您的“父列表”,并且您会知道如何做 - 只需创建一个子列表以添加到父列表..:D

【讨论】:

    【解决方案2】:
    for (Integer i: listOfIntegers) {
     List<Integer> list = new LinkedList<Integer>();
     list.add(i);
     listOfLists.add(list);
    }
    

    这个解决方案基本上是在列表的初始列表中添加一个新列表,其中整数列表中的每个整数都有一个元素

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 1970-01-01
      • 2014-06-16
      • 2017-09-09
      • 2015-08-13
      相关资源
      最近更新 更多