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!