Java 在清除arrayList时遇到问题

Java 在清除arrayList时遇到问题,java,arraylist,Java,Arraylist,我有一个2d arraylist,在一个循环中,我想将2d列表中的每个1d列表解析为一个临时列表。另外,在每次迭代结束时,我希望清除这个临时列表,以便下一步解析初始2d的I-est列表 该守则的内容如下: List<List<Integer>> conVert = new ArrayList<List<Integer>>(); List<Integer> temp = new ArrayList<Integer>();

我有一个2d arraylist,在一个循环中,我想将2d列表中的每个1d列表解析为一个临时列表。另外,在每次迭代结束时,我希望清除这个临时列表,以便下一步解析初始2d的I-est列表

该守则的内容如下:

 List<List<Integer>> conVert = new ArrayList<List<Integer>>();
 List<Integer> temp = new ArrayList<Integer>();
 for (int i = 0; i<conVert.size(); i++){
    temp.addAll(conVert.get(i));
    Collections.sort(temp);
    System.out.println(temp);

    for(int j = 0; j<temp.size(); j++){
        // several commands
    }
    temp.clear();
 }
List conVert=new ArrayList();
List temp=new ArrayList();

for(int i=0;i您可以使用全新的
列表
而不是清除“旧”列表。为什么在for循环之后需要一个空的
列表
?重用这些基本数据结构没有任何好处,甚至可能产生相反的效果

当您的
列表超出范围时,它将被垃圾收集,几乎不需要任何成本,而显式清空它需要一些资源

编辑:我想在这种情况下,最好让代码自己说话:

 List<List<Integer>> conVert = new ArrayList<List<Integer>>();

 for (int i = 0; i<conVert.size(); i++){
    List<Integer> temp = new ArrayList<Integer>();
    temp.addAll(conVert.get(i));
    Collections.sort(temp);
    System.out.println(temp);

    for(int j = 0; j<temp.size(); j++){
        // several commands
    }
}
List conVert=new ArrayList();

对于(int i=0;我建议您尝试在调试器中运行代码。我可以向您保证List.clear()确实有效,并且已经测试/使用多年了。)当你在每次迭代中创建一个新的
temp
时会发生什么?问题是否消失?问题是,在每次迭代中,这些代码在temp中添加一个新列表,因此如果conVert.get(0)=[1,2],那么在第一个iter temp=[1,2]中conVert.get(1)=[3,4],在第二个iter temp=[1,2,3,4]@zenitis上面的代码不是实际的代码吗?@zenitis上面的代码试图在每次i创建后清除列表,这不是你在评论中所说的那几个命令是什么?如果它们不改变temp,那么是你的2d列表格式不正确。我得到的是在temp列表中解析第二个conVert列表在第一步中,我想解析第一个conVert.get(0)int-temp列表,在第二次迭代中解析第二个list conVert.get(1)e.c。t@zenitis我想,最好用代码(一如既往:)来说明我的观点。请在我的编辑中尝试修改过的代码,看看它是否适合你。