In the code below
// Assume there are non-null string arrays arrayA and arrayB
// Code 1
ArrayList<String[]> al = new ArrayList<String[]>();
String[] tmpStr = new String[2];
for (int ii = 0; ii < arrayA.length; ii++) {
tmpStr[0] = arrayA[ii];
tmpStr[1] = arrayB[ii];
al.add(ii, tmpStr);
}
// Code 2
ArrayList<String[]> al = new ArrayList<String[]>();
for (int ii = 0; ii < arrayA.length; ii++) {
String[] tmpStr = new String[2];
tmpStr[0] = arrayA[ii];
tmpStr[1] = arrayB[ii];
al.add(ii, tmpStr);
}
Code 2 gives the wanted results — that is, al now contains {arrayA(ii), arrayB(ii)} for each of its index. In code 1, however, al contains {arrayA(last_index), arrayB(last_index)} for all of its indices. Why is that?
In the first code block, you declare the string array with size of 2. So it’s defined in memory at once and in the loop you assign the values to that reference so on each loop step, its value is changed and it’ll be added into the
ArrayListobject.I the second code block, inside the loop you initialize the string array, so every time it will create new array object in memory and all the objects will have different references with different values added to them, that will be passed on to the
ArrayListobject.That’s why you get the different values here.