我一直在尝试将整数列表插入另一个列表,但似乎我犯了一些错误,我的输出不正确有人可以帮忙吗? 也可以评论http://goo.gl/xdLP9H
public class ListInsideList {
public static void main(String[] args) {
List<List<Integer>> newList = new ArrayList<List<Integer>>();
List<Integer> tempList = new ArrayList<Integer>();
List<Integer> originalList = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
originalList.add(i);//adding values to list
}
for(Integer value : originalList){
tempList.add(value);
if(tempList.size()==5)
{
newList.add(tempList);
System.out.println("iteration:"+newList);
tempList.clear();//clearing list
}
}
System.out.println("final:"+newList);
}
}
输出:
iteration:[[6, 7, 8, 9, 10], [6, 7, 8, 9, 10]]
final :[[], []]
required is:iteration:[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
final:[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
最佳答案
您的最终答案需要有 2 个单独的列表。
-
[1, 2, 3, 4, 5] // List One
-
[6, 7, 8, 9, 10] // List Two
那么您在哪里创建这两个单独的列表?你没有,你只是在重复使用相同的 tempList
在每次迭代中。添加tempList
到另一个List
不会将它与“tempList”的变量名称分开,后者是对您随后使用的同一对象的引用 clear()
.
而不是 clear()
, 每次创建一个新的:
- 代替
tempList.clear(); //clearing list
- 使用
tempList = new ArrayList<>(); // new List
关于java - 列表列表但输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35674445/