首页 > 解决方案 > 有没有办法清除 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 表达式中使用时,我不能将它重新分配为nullor new ArrayList<>() (否则它会起作用)。

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

标签: javaarraylistcollectionsgarbage-collection

解决方案


虽然这个答案解决了在另一个列表中清除列表的问题,但真正的答案在Turing85 的评论中,即不需要 clear temp,因为temp是本地的。


如果您想清除temp而不清除该列表中已插入的条目,list2则不能先插入temp然后list2清除temp,因为两者temp中的条目list2都指向同一个列表。

相反,插入一个副本:

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

那么当你清除时temp,你放入的新列表list2将不受影响。


推荐阅读