[英]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
,我无法将其重新分配为null
或new 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
,因为temp
和list2
的条目都指向同一个列表。
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.