Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating arraylist of arrays

I'm trying to create an array list of string arrays. When I am done, I want the array list to look like this:

[0,0], [0,1], [1,0], [1,1,]

I have tried to define an array and then add it to the array list. Then re-define an array and add it again. But the array list only seems to contains the last entry. Take a look:

String[] t2 = new String[2]; 

ArrayList<String[]> list2 = new ArrayList<String[]>();

t2[0]="0";
t2[1]="0";
list2.add(t2);
t2[0]="0";
t2[1]="1";
list2.add(t2);
t2[0]="1";
t2[1]="0";
list2.add(t2);
t2[0]="1";
t2[1]="1";
list2.add(t2);

for (String[] tt : list2) 
{
System.out.print("[");
for (String s : tt)
System.out.print(s+" ");
System.out.print("]");
}

The output is:

[1,1] [1,1] [1,1] [1,1]

Any idea on how to add each array to my array list?`

like image 336
kjm Avatar asked Aug 16 '13 16:08

kjm


2 Answers

The problem is that you are adding the same object to each index of your ArrayList. Every time you modify it, you are modifying the same object. To solve the problem, you have to pass references to different objects.

String[] t2 = new String[2]; 

ArrayList<String[]> list2 = new ArrayList<String[]>();

t2[0]="0";
t2[1]="0";
list2.add(t2); 

t2 = new String[2]; // create a new array
t2[0]="0";
t2[1]="1";
list2.add(t2);

t2 = new String[2];
t2[0]="1";
t2[1]="0";
list2.add(t2);

t2 = new String[2];
t2[0]="1";
t2[1]="1";
list2.add(t2);
like image 125
ktm5124 Avatar answered Oct 20 '22 09:10

ktm5124


You are adding the same array t2 over and over. You need to add distinct arrays.

ArrayList<String[]> list2 = new ArrayList<String[]>();

list2.add(new String[] {"0", "0"});
list2.add(new String[] {"0", "1"});
list2.add(new String[] {"1", "0"});
list2.add(new String[] {"1", "1"});

As an aside: you can use Arrays.toString(tt) inside the loop to format each String[] the way you are doing.

like image 32
Ted Hopp Avatar answered Oct 20 '22 08:10

Ted Hopp