Java string array initiation in and outside of the loop structure
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];
开发者_JAVA百科 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.
You might want to draw a picture here.
In both cases you have an array with several elements. In the first case, each array element in al
is pointing to the exact same object. The value of this shared object (a two-element array) keeps getting written to; at the end of your code fragment it holds the last two values assigned to it. In the latter, each array element in al
is pointing to a completely different object. Each of these objects are created on different passes through your loop.
Try it. Drawing these diagrams is very illuminating.
In case1 you will only crate String array. Look at how many times the new
keyword is used in the two cases. In the second case for every iteration crating several arrays in the first case one time creating only on array.
tmpStr[]
is pointing to same array which you created by new String[2];
each time. Se each time when you are modifying the tmpStr[]
contents its overriding the earlier values as array is mutable.
in code 1 only once memory allocated. and on same memory array intialized twice on same memory location. list contains reference to that array. It will always fetch data from that array location so it will give lastly intialized array It . so we lost fistly inserted data.
But in code 2 two seperate array in with different memory location. so references are different. so proper answer.
精彩评论