0

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?

devmax
  • 47
  • 8

2 Answers2

2

In java, everything is passed by value. The primitive or reference type is evaluated, and its value\reference value is passed. when you do float[] foo = new float[5], you create a reference variable foo, which contains link to new float[5] object. When you do foo=null, you make the foo reference variable to contain a null-reference, but it doesn't affect the object you created with new float[5], you just remove the reference from foo var

why does arr not end up with null values after the for loop? Cause in your for loop you added those arrays into the ArrayList<float[]> arr, so it is containing all of your inserted arrays as its elements.

secario
  • 456
  • 4
  • 14
0

For the same reason that after:

int foo = 11;
int bar = foo;
foo = 12;

bar is still 11.

The second line says "assign to bar the value foo has right now". It doesn't matter when foo gets another value afterwards.

For the same reason, in your program, you add to the arraylist the value foo had at that point, that is, a reference to some array. All copies of the same reference do reference the same object (here: the array). Therefore we have now 2 references to the same single array, and we can change that array through either reference. At the end you set foo to null. This overwrites the variable foo, so that now there is only one reference to our changed array.

What you are confusing: foo is not the array itself, it is just a reference to the array.

Ingo
  • 36,037
  • 5
  • 53
  • 100