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,]
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);
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.
You are only creating one array, and putting its reference repeatedly into the ArrayList.
Instead, you can create a new array for each element in the List:
ArrayList<String[]> list2 = new ArrayList<String[]>();
String[] t2;
t2 = new String[2];
t2[0]="0";
t2[1]="0";
list2.add(t2);
t2 = new String[2];
t2[0]="0";
t2[1]="1";
list2.add(t2);
t2 = new String[2];
t2[0]="1";
t2[1]="0";
t2 = new String[2];
list2.add(t2);
t2[0]="1";
t2[1]="1";
list2.add(t2);
You have just one item (t2) and each time you add it to the ArrayList . actually the reference of t2 is going to be saved in ArrayList so when you change the t2 value all of references in the ArrayList take effect.
This is because you're adding t2 to all of the entries. Each time you overwrite t2 you're changing all the values. This is because t2 isn't being passed by value, it is being passed by reference and saved by reference.