1

Expected output : Cell-1 Cell-2 Cell-3 Cell-4

But the output that I am getting is : Cell-3 Cell-4 Cell-3 Cell-4

Why is this happening?

import java.util.ArrayList;

public class Test {
public static void main(String... a) {
    String[][] var1 = new String[] []{{"Cell-1","Cell-2"},{"Cell-3","Cell-4"}};
    ArrayList<String> r = new ArrayList<String>();
    ArrayList<ArrayList<String>> var = new ArrayList<ArrayList<String>>();

    //Insering data into the ArrayList.
    for(String[] row : var1){
        r.clear();
        for(String data : row){
            r.add(data);
        }
        var.add(r);
    }

    //Print data to console.
    for(ArrayList<String> r1 : var){
        for(String cell : r1)
            System.out.print(cell+" ");
        System.out.println();
    }
}

} `

2
  • This is not an answer. You should use List<List<String>> instead. Commented Apr 11, 2013 at 10:14
  • @adarshr : What is the advantage of using List<List<String>> over ArrayList<ArrayList<String>> ? Commented Apr 11, 2013 at 10:34

1 Answer 1

3

This is not unexpected at all: you add the same object, namely ArrayList r, to the ArrayList var twice. First, you add it when it has Cell-1 Cell-2, then you clear it, and then you add it with Cell-3 Cell-4. The problem is, when you call r.clear(), the array list that you added to var gets cleared as well.

You need to create a new ArrayList instead of clearing the existing one to fix this problem: replace r.clear() with r = new ArrayList<String>(), and the problem will go away.

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

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.