user6447244 user6447244 - 5 months ago 7
Java Question

Inserting ArrayLists into ArrayLists

I don't really know how to ask this without creating confusion, but I'll try.

In my Swing application I want to add an ArrayList to an ArrayList and then clear(); the second ArrayList without all the data being lost.
Here's an example:

ArrayList<ArrayList<String>> aList1 = new ArrayList<>();
ArrayList<String> aList2 = new ArrayList<>();
aList2.add("Object 1");
aList2.add("Object 2");
aList1.add(aList2);
aList2.clear();
System.out.println(aList1);


But then all the data is lost and aList1 is empty. I assume this is because I add the ArrayList as ArrayList and not as values. Is it possible to save the data in aList1 while deleting it from aList2, thus making space for future use.

Answer

Simply Create new ArrayList From the ArrayList you want to add.

Here is it

   ArrayList<ArrayList<String>> aList1 = new ArrayList<>();
   ArrayList<String> aList2 = new ArrayList<>();
   aList2.add("Object 1");
   aList2.add("Object 2");
   aList1.add(new ArrayList(aList2));
   aList2.clear();
   System.out.println(aList1);