konstantin konstantin - 1 month ago 11
Java Question

Add an arraylist to 2d arraylist in java

I have a 2D arraylist which I want to fill it with several 1D arraylists. My code is the following:

ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
while (ts2.next()) {

list.add( ts2.getString("userName");
list.add(ts2.getString("userId"));
array.add(list);
list.clear();

}


I have noticed that list.clear() deletes the elements from the list however also deletes the element from the array. In the end both array and list are empty. How can I add list in array and clear the list after array.add(list);

Answer

You can clone the list:

array.add(list.clone());

Or you can instantiate the list object within the loop itself:

    ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>(); 

    while (ts2.next()) {
        ArrayList<String> list = new ArrayList<String>();
        list.add( ts2.getString("userName");
        list.add(ts2.getString("userId"));  
        array.add(list);
    }

Then you wouldn't even need to clear it.