Java – Is there a way to clear the arraylist but not respect the memory reference?

Is there a way to clear the arraylist but not respect the memory reference?… here is a solution to the problem.

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

Here is the relevant part of my code:

<pre class=”lang-java prettyprint-override”> 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 temporary files
before recursively calling process
The problem here is that my list2 becomes empty temp after empty.
Because I’m using temp in a lambda expression, I can’t reassign it as null or new ArrayList<>().
(Otherwise it will work).

I’d have thought about creating a new list and copying between temporary list and new list, but it doesn’t feel like a suitable approach.
Is there another way?

Solution

While this answer solves the problem of clearing a list when it’s in another list, the real answer is in Turing85’s comment. You do not need to clear temp because temp is local.


If you want to clear temp without clearing the entries in the list you inserted in list2, you can’t insert temp into list2 and then clear temp because temp and list2 The entries in all point to the same list.

Instead, insert a copy:

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

Then when you clear temp, the new list you put into list2 will not be affected.

Related Problems and Solutions