0

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?

  • 3
    `listDataOne.clear();`? I think you assume that the inner list and its values are copied when you put it into the outer list. But they're not. You `add` a reference. Therefore calling `clear` on the list inside the loop body will change the inner list because it's the same instance. – akuzminykh Jul 22 '20 at 14:00

2 Answers2

2

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.

John Smith
  • 427
  • 6
  • 17
0

It's happing because listData is storing reference of listDataOne instead of value. So, when you clear the reference will have no value and when you update listDataOne all the reference to it will be updated.

    String content1;
    String content2;

    ArrayList<ArrayList<String>> listData = new ArrayList<>();
    ArrayList<String> listDataOne;

    for (int i = 0; i < 3; i++) {
        listDataOne = new ArrayList<>();
        content1 = "one " + i;
        content2 = "two " + i;

        listDataOne.add(content1);
        listDataOne.add(content2);

        System.out.println(listDataOne);
        listData.add(listDataOne);
        System.out.println(listData);  
  }
    System.out.println(listData);  

You should also go through this this post.

Ankit Chauhan
  • 646
  • 6
  • 20
  • I would also move the declaration of `listDataOne` into the loop to reduce the scope. It doesn't need to exist outside the loop. – Mark Rotteveel Jul 22 '20 at 18:15