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?
Java arrays are mutable. Your code is adding a single array multiple times, and modifying the same array on each iteration.
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 ArrayList object.
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 ArrayList object.
That's why you get the different values here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With