0

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)

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I got this message: The method add(ArrayList<String>) in the type ArrayList<ArrayList<String>> is not applicable for the arguments (Object)
Try to cast the object as an arraylist: array.add((ArrayList<String>)list.clone());
array.add(list.clone()); don't work
@adeeliqbal Not sure why it wouldn't work. You're adding an arraylist into an arraylist of arraylists.
1

You can do this:

    ArrayList<String[]> arr = new ArrayList<String[]>();
    String[] str = new String[2];
    while (ts2.next()) {
        str[0] = ts2.getString("userName");
        str[1] = ts2.getString("userId");  
        arr.add(str);
    }

if you would an arraylist also:

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

Comments

1

You can create a new instance of ArrayList<> to be added in the existing one.

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

However the better approach is to map these values into a new instance of a class.

List<MyClass> = new ArrayList<>();

while (ts2.next()) {
    MyClass i = new MyClass(ts2.getString("userName"), ts2.getString("userId"));
    array.add(i);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.