这是我代码的相关部分:
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));
}
在递归调用 process
之前我必须清除临时文件.
这里的问题是,我的 list2
清空后变空 temp
.
因为我正在使用 temp
在 lambda 表达式中,我无法将其重新分配为 null
或 new ArrayList<>()
(否则它会起作用)。
我想过创建一个新列表并在临时列表和新列表之间进行复制,但感觉这不是一个合适的方法。
还有其他方法吗?
最佳答案
虽然这个答案解决了当列表在另一个列表中时清除列表的问题,但真正的答案在 Turing85's comment 中。不需要清除 temp
,因为 temp
是本地的。
如果你想清除 temp
而不清除你在 list2
中插入的那个列表中的条目,你不能插入 temp
进入 list2
然后清除 temp
,因为 temp
和 list2
中的条目都指向 相同的列表。
相反,插入一个副本:
list2.add(new ArrayList<>(temp));
然后当您清除 temp
时,您放入 list2
的新列表将不受影响。
关于java - 有没有办法清除 arraylist 但不尊重内存引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920091/