Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java adding data to a nested array

Tags:

java

arraylist

How can I use the same arraylist row to add values into the nested array tableValues since the clear command removes the data in row.

Thanks

    ArrayList<ArrayList<String>> tableValues = new ArrayList<ArrayList<String>>();
    ArrayList<String> row = new ArrayList<String>();

    row.add("a");
    row.add("b");
    row.add("c");
    tableValues.add(row);
    row.clear();

    row.add("d");
    row.add("e");
    row.add("f");
    tableValues.add(row);
    row.clear();

    row.add("g");
    row.add("h");
    row.add("i");
    tableValues.add(row);
    row.clear();

    System.out.println(tableValues);
like image 328
Ricco Avatar asked Jun 29 '26 09:06

Ricco


1 Answers

I'm sure you really want to add three different ArrayLists, so change each row.clear() to:

row = new ArrayList<String>();

Why would you want to "use the same arraylist row to add values"? I can't see why you'd want your top-level ArrayList to basically contain the same reference three times. Why would you not want them to be references to independent lists?

like image 72
Jon Skeet Avatar answered Jul 01 '26 22:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!