I run the following program in Java:
public class foobar {
public static void main(String[] args) {
ArrayList<float[]> arr = new ArrayList<float[]>(10);
for (int i=0; i<10; i++){
int k = i + 10;
float[] foo = new float[5];
foo[2] = k;
//System.out.println(Arrays.toString(foo));
arr.add(foo);
foo[0] = 11;
foo = null;
}
for (float[] item:arr) {
System.out.println(Arrays.toString(item));
}
}
}
and it outputs,
[11.0, 0.0, 10.0, 0.0, 0.0]
[11.0, 0.0, 11.0, 0.0, 0.0]
[11.0, 0.0, 12.0, 0.0, 0.0]
[11.0, 0.0, 13.0, 0.0, 0.0]
[11.0, 0.0, 14.0, 0.0, 0.0]
[11.0, 0.0, 15.0, 0.0, 0.0]
[11.0, 0.0, 16.0, 0.0, 0.0]
[11.0, 0.0, 17.0, 0.0, 0.0]
[11.0, 0.0, 18.0, 0.0, 0.0]
[11.0, 0.0, 19.0, 0.0, 0.0]
From what I understand, Arraylist only stores a reference to the object (a float array in this case). However, since array foo is only valid within the for loop's scope in this case, why does arr not end up with null values after the for loop? Why is the change foo[0]=11
reflected, but not foo=null
?