I am trying to nest data into a list, which I also add to another list. The challenge is to get a list of nested lists of data.
String content1;
String content2;
ArrayList<ArrayList<String>> listData = new ArrayList<>();
ArrayList<String> listDataOne = new ArrayList<>();
for (int i = 0; i < 3; i++) {
content1 = "one " + i;
content2 = "two " + i;
listDataOne.add(content1);
listDataOne.add(content2);
System.out.println(listDataOne);
listData.add(listDataOne);
System.out.println(listData); // [[one 2, two 2], [one 2, two 2], [one 2, two 2]]
listDataOne.clear();
}
System.out.println(listData); // [[], [], []]
But in the end, I get empty nested lists. What am I doing wrong?
Advertisement
Answer
At the end of your for loop you’re clearing listDataOne and since listData has the same list reference, it gets cleared too. You need to replace
listDataOne.clear();
with
listDataOne = new ArrayList<>();
to preserve data.