-1

I am trying to store a tempList in bigList but after using clear nothing is getting stored.

So what i am trying to do is store a list of list inside bigList, but after storing the tempList in bigList I want to populate new data in tempList and again store it in biglist.

import java.util.ArrayList;
import java.util.List;

public class Demo {


    public static void main(String [] args){

        List<List<String>> bigList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        list2.add("2");

        List<String> list3 = new ArrayList<>();
        list3.add("3");



            tempList.addAll(list2);

            bigList.add(tempList);

            tempList.clear();

            tempList.addAll(list3);

            bigList.add(tempList);

            tempList.clear();

        for(int i=0;i<bigList.size() && !bigList.isEmpty();i++){
            if(!bigList.get(i).isEmpty())
            System.out.println(bigList.get(i).get(0));
        }


    }
}
marco525
  • 50
  • 11
  • What is your expected output and what are you getting? – Thiyagu Nov 15 '19 at 05:21
  • Expected Output : 2,3 But not getting any result, am not worried about the output, i want to know what am i doing wrong here, ideally it should work. – marco525 Nov 15 '19 at 05:22

1 Answers1

0

code

    public static void main(String [] args){

        List<ArrayList<String>> bigList =  new ArrayList<ArrayList<String>>(); //what you missed
        List<String> tempList = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        list2.add("2");

        List<String> list3 = new ArrayList<>();
        list3.add("3");



            tempList.addAll(list2);

            bigList.add(new ArrayList<String>(tempList)); //adding to array

            tempList.clear();

            tempList.addAll(list3);

            bigList.add(new ArrayList<String>(tempList));

            tempList.clear();

        for(int i=0;i<bigList.size() && !bigList.isEmpty();i++){
            if(!bigList.get(i).isEmpty())
            System.out.println(bigList.get(i).get(0));
        }


    }
}

result

2

3

please go through other posts before posting a question Working with a List of Lists in Java

you can further reduce the line of code.

Madhu Nair
  • 428
  • 1
  • 7
  • 20
  • Care to Explain why you have added this line: List> bigList = new ArrayList>(); //what you missed As it is working without this correction? bigList.add(new ArrayList(tempList)); //adding to array And why we need to create new ArrayList Object, its just like creating a new variable not reusing the same object i.e tempList And am not sure how the link you have mentioned is related to my post,cause they are using new templist – marco525 Nov 15 '19 at 06:11