Dhyey Shah
Dhyey Shah

Reputation: 652

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.
Issue here is, my list2 gets empty, upon clearing 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).

I thought of creating a new List and copying between temp and new List, but it doesn't feel like a proper approach.
Is there any other way to do this?

Upvotes: 3

Views: 837

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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.


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.

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.

Upvotes: 3

Related Questions