Java – How to clear one variable (array list list) without inadvertently clearing another variable?

How to clear one variable (array list list) without inadvertently clearing another variable?… here is a solution to the problem.

How to clear one variable (array list list) without inadvertently clearing another variable?

To be clear, I have a 3D ArrayList that I’m going to use: to hold multiple 2D ArrayLists.

3D ArrayList (that’s what I mean when I say 3D ArrayList):

ArrayList<ArrayList<ArrayList<String>>> main_Functions = new ArrayList<>();

2D ArrayList (when I say 2D ArrayList, that’s what I mean:

).

ArrayList<ArrayList<String>> localValues = new ArrayList<>();

But after adding each 2D ArrayList, I’m going to clear the variable that holds the original 2D ArrayList. So old information does not interfere with newly added information, etc. But after I cleared the variable that saved the original 2D ArrayList (what was added to the 3D ArrayList), the data added to the 3D ArrayList was deleted.

My code is as follows:

ArrayList<ArrayList<String>> localValues = new ArrayList<>();
ArrayList<ArrayList<ArrayList<String>>> main_Functions = new ArrayList<>();

if (arrayListNotEmpty(localValues)) {
                main_Functions.add(localValues);
                localValues.clear();
          }

How do I fix this?
So the information added to the 3D ArrayList is preserved in the clearance of the 2D ArrayList?

Solution

Your situation basically goes something like this: (I removed the first-level ArrayList to make it clearer).

ArrayList<String> inner = new ArrayList<>();
ArrayList<ArrayList<String>> outer = new ArrayList<>();

inner.add("Hello World!");
outer.add(inner);
System.out.println(outer.get(0));  prints [Hello World!]
inner.clear();
System.out.println(outer.get(0));  prints [] i.e. an empty list

Or, simpler:

ArrayList<String> a = new ArrayList<>();
a.add("Hello World!");

ArrayList<String> b = a;

System.out.println(b);  prints [Hello World!]
a.clear();
System.out.println(b);  prints []

This is because a and b do not contain an ArrayList. In Java, if we say that a variable contains an ArrayList, we actually mean that it contains a reference to an ArrayList.

In other words, a actually contains “ArrayList #1234” or something similar. b also contains “ArrayList #1234”. a.clear() line clears ArrayList #1234,System.out.println(b); Line prints the contents of ArrayList #1234 (which we just cleared).

Instead, you can always create a new ArrayList to copy it.

For example, instead

main_Functions.add(localValues);

You can do something similar

ArrayList<ArrayList<String>> localValues_copy = new ArrayList<>(localValues);
main_Functions.add(localValues_copy);

or shortened:

main_Functions.add(new ArrayList<>(localValues));

This adds a reference to the brand new ArrayList to your 3D ArrayList, rather than to the same array referenced by localValues.

Related Problems and Solutions