1

I'm new to java, and I want to have an ArrayList (mainList) of ArrayLists of Strings, with an unknown number sets of strings that can only be extracted as individual strings, not all together as a list.

My idea was to repeatedly append each string of a set to an ArrayList (list2), append list2 to the end of mainList, then empty the ArrayList, then append each string of the next set to list2, append that one, empty the list, repeat. I've included an example of what I tried to execute:

    private ArrayList<ArrayList<String>> mainList = new ArrayList<>();

    private ArrayList<String> list2 = new ArrayList<>();



for (int i = 0; i < items.size(); i++){

     for (int j = 0; j < items.get(i).innerItem.size(); j++){

          list2.add(items.get(i).innerItem.get(j).string);
     }

     mainList.add(list2);

     list2.clear();
}

let's say that there are 2 items, having innerItem 1 with strings "haha" and "hehe", and innerItem2 with strings "chuckle" and "what"

mainList then has two lists in it, both of which are "chuckle" and what"

The mainList ends up having multiple lists of all the same array: the last list that was appended. The Clear function seems to clear both the list2 and the mainList section that was appended. How do I make it so that the lists stay different? Thanks in advance!

qyyao
  • 35
  • 7

2 Answers2

0

You currently add one single ArrayList<String> list2 multiple times into mainList since it always stays the same object and it stays empty since you clear list2 everytime you reach the end of the loop.

If I understand your question right your problem should be solved by using this code:

private ArrayList<ArrayList<String>> mainList = new ArrayList<>();

for (int i = 0; i < items.size(); i++) {
     ArrayList<String> list2 = new ArrayList<>();
     for (int j = 0; j < items.get(i).innerItem.size(); j++) {
          list2.add(items.get(i).innerItem.get(j).string);
     }
     mainList.add(list2);
}

Now a new ArrayList is created for each entry of your items-List and added to mainList

Nicola Uetz
  • 848
  • 1
  • 7
  • 25
0

list2 is an object and, like all objects, acts like a reference type. What that means is if you append list2 to mainList, and then clear list2, that will also clear the list you just appended to mainList. When you then change list2 to hold other values, it will also change the content of the appended list within mainList.

In the end, you've appended list2 a bunch of times, and each simply refers to the same memory address as the original list2 object. As such, they are all the same.

To fix this, you can either create a clone of list2 and append that clone rather than list2 itself, or overwrite list2 as a new list each iteration by construction.

Option 1:

mainList.add(new ArrayList<>(list2));
list2.clear();

Option 2:

mainList.add(list2);
list2 = new ArrayList<>();
Alexander Guyer
  • 2,063
  • 1
  • 14
  • 20