3

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);

2 Answers 2

3

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?

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

2 Comments

What I meant was I didn't want to have row1, row2 row3 etc since I don't know how many rows there are, so that would cause a problem :)
@Ricco: Right - it's worth differentiating between objects and variables. You're now using one variable, but it will have three different values over its lifetime. (I'd be tempted to refactor the "add a row" part into a separate method, but that's a slightly different topic where I'd need more context.)
0

Use something like

ArrayList<String> row;

row = new ArrayList<String>();
// fill row
tableValues.add(row);

row = new ArrayList<String>();
// fill row
tableValues.add(row);

This way you don't need in your code variable for each row. or put it in cycle

while(codnition) { // or for or do {} while(condition);
   List<String> row = new  ArrayList<String>();
   // fill row
   table.add(row);
}

This way there single name for currently added row, but scope of this variable is only inside given iteration of cycle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.