gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:16:19 24 4
gpt4 key购买 nike

这是我代码的相关部分:

    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 表达式中,我无法将其重新分配为 nullnew ArrayList<>() (否则它会起作用)。

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

最佳答案

虽然这个答案解决了当列表在另一个列表中时清除列表的问题,但真正的答案在 Turing85's comment 中。不需要清除 temp,因为 temp 是本地的。


如果你想清除 temp 而不清除你在 list2 中插入的那个列表中的条目,你不能插入 temp 进入 list2 然后清除 temp,因为 templist2 中的条目都指向 相同的列表。

相反,插入一个副本:

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

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

关于java - 有没有办法清除 arraylist 但不尊重内存引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com