有没有办法清除 arraylist 但不尊重内存引用?

Is there a way to clear arraylist but not deference the memory reference?

这是我的代码的相关部分:

    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 后变空了。
因为我在 lambda 表达式中使用 temp,所以我无法将其重新分配为 nullnew ArrayList<>() (否则它会起作用)。

我想创建一个新列表并在临时列表和新列表之间进行复制,但感觉这不是一个合适的方法。
还有其他方法吗?

虽然这个答案解决了当列表在另一个列表中时清除列表的问题,但真正的答案是 没有必要清除 temp,因为 temp 是本地人。


如果您想清除 temp 而不清除您在 list2 中插入的列表中的条目,则不能将 temp 插入 list2然后清除 temp,因为 templist2 中的条目都指向 same 列表。

而是插入一个副本:

list2.add(new ArrayList<>(temp));

然后当您清除 temp 时,您放入 list2 的新列表将不受影响。