java - 有没有办法清除 arraylist 但不尊重内存引用?
问题描述
这是我的代码的相关部分:
List<List<String>> list2 = new ArrayList<>();
public void process(List<String> z) {
if (z.size() > 0) {
String x = z.get(0);
List<String> temp = new ArrayList<>();
z.stream().filter(e -> !e.equals(x)).forEach(e -> {
// some operations on temp
});
list2.add(temp); // adding temp to list2
z.removeIf(e -> temp.contains(e));
temp.clear(); // clearing temp
z.forEach(System.out::println);
list2.forEach((System.out::println)); // empty list2
process(z);
list2.forEach(e -> process(e));
}
我必须在递归调用之前清除 temp process
。
这里的问题是,清除后我list2
的空了temp
。
当我temp
在 lambda 表达式中使用时,我不能将它重新分配为null
or new ArrayList<>()
(否则它会起作用)。
我想过创建一个新列表并在临时列表和新列表之间进行复制,但感觉不是一个合适的方法。
有没有其他方法可以做到这一点?
解决方案
虽然这个答案解决了在另一个列表中清除列表的问题,但真正的答案在Turing85 的评论中,即不需要 clear temp
,因为temp
是本地的。
如果您想清除temp
而不清除该列表中已插入的条目,list2
则不能先插入temp
然后list2
清除temp
,因为两者temp
中的条目list2
都指向同一个列表。
相反,插入一个副本:
list2.add(new ArrayList<>(temp));
那么当你清除时temp
,你放入的新列表list2
将不受影响。