简体   繁体   English

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

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

This is the relevant part of my code:这是我的代码的相关部分:

    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));
    }

I have to clear temp before recursively calling process .我必须在递归调用process之前清除 temp 。
Issue here is, my list2 gets empty, upon clearing temp .这里的问题是,我的list2在清除temp变空。
As i am using temp inside the lambda expression, i cannot re-assign it as null or new ArrayList<>() (otherwise it would have worked).当我在 lambda 表达式中使用temp ,我无法将其重新分配为nullnew ArrayList<>() (否则它会起作用)。

I thought of creating a new List and copying between temp and new List, but it doesn't feel like a proper approach.我想创建一个新的 List 并在 temp 和 new List 之间进行复制,但感觉这不是一种正确的方法。
Is there any other way to do this?有没有其他方法可以做到这一点?

While this answer addresses the issue of clearing the list when it's in another list, the real answer is in Turing85's comment that there's no need to clear temp , since temp is a local.虽然这个答案解决了在另一个列表中清除列表的问题,但真正的答案是在Turing85 的评论中,没有必要清除temp ,因为temp是本地的。


If you want to clear temp without clearing the entries on that list that you've inserted in list2 , you can't insert temp into list2 and then clear temp , because temp and the entry in list2 both point to the same list.如果要清除temp而不清除已插入list2列表中的条目,则不能将temp插入list2然后清除temp ,因为templist2的条目都指向同一个列表。

Instead, insert a copy:相反,插入一个副本:

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

Then when you clear temp , the new list you've put in list2 will be unaffected.然后当您清除temp ,您放入list2的新列表将不受影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM