Reputation: 13
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();
}
}
} `
Upvotes: 1
Views: 145
Reputation: 726479
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.
Upvotes: 3