How do I declare a 2D String arraylist?

I want to do something like this ArrayList<String<String>> mylist

How can I create it?

How can I add to the external and internal list

and how can I convert the internal list to a simple array list?


You can go with

List<List<String>> ls2d = new ArrayList<List<String>>();
List<String> x = new ArrayList<String>();
x.add("Hello");
x.add("world!");
ls2d.add(x);

System.out.println(Arrays.deepToString(ls2d.toArray()));

The first array list isn't an array list of String, it's an ArrayList of ArrayList.

ArrayList<ArrayList<String>>

List<List<String>> array = new ArrayList<List<String>>();
...
array.add(new ArrayList<String>())
array.get(0).add("qqq");

array.get(0) - is a internal list


List<List<String>> super2dArray = new ArrayList<ArrayList<String>>()

This is an arraylist of arraylists holding strings.

Also ArrayList<String<String>> mylist makes no sense, because String is not a collection/list, but I think you understood that. Future readers might not though.

See this answer to see why I chose to have List on the left side.


There are two ways to achieve what you desire. I am providing code snippet for both:

1.List<List<String>> lol = new ArrayList<List<String>>();

Scanner in = new Scanner(System.in);
int size = in.nextInt();

//Declare your two dimensional ArrayList of Strings. 
List< List<String>> lol = new ArrayList<List<String>>();

//Instantiate and Populate
for (int i=0;i<size;i++){
    int internalListSize = in.nextInt(); //the size of each internal list
    lol.add(new ArrayList<String>());
    for (int j=0;j<internalListSize;j++){
        String whateverYouWanttoPut = in.nextLine();
        lol.get(i).add(whateverYouWanttoPut);
    }
}

//Access Elements 
try {
    System.out.println(lol.get(0).get(4));
    System.out.println(lol.get(1).get(2));
    System.out.println(lol.get(3).get(2));
} catch (Exception e){
    System.out.println("ERROR!");
}     

2. ArrayList[] set = new ArrayList[n];

Scanner in = new Scanner(System.in);
int size = in.nextInt();
//Declare your two dimensional ArrayList of Strings.
ArrayList[] set = new ArrayList[size];

//Populate it. 
for(int i=0;i<size;i++){
    int innerSize = in.nextInt();
    set[i] = new ArrayList<String>();
    for(int j=0;j<innerSize;j++){  
        set[i].add(in.nextLine());                
    }
}        
try{
    System.out.println(set[0].get(1));
    System.out.println(set[1].get(2));
} catch(Exception e){
    System.out.println("ERROR!");
}