If I have a 2d array of objects, and want to initialize them all, I call a loop, eg:
for(int i=0; i<len; i++)
for(int j=0; j<len; j++)
objects[i][j] = new MyObject();
Which works fine, but when I tried doing this with the for-each construct, it didn’t work and the entire array remains null:
for(MyObject[] intermediate: objects)
for(MyObject obj: intermediate)
obj = new MyObject();
How come they behave differently?
The assigment
just set a new object in the variable
obj, and does not change the value in the array, it only changes the reference variableobj.What happens is that
objects[i][j]is assined toobj, and then you change the value ofobj, without changing the actual array.when you assign directly to
objects[i][j]– it works as expected, since you change the value ofobjects[i][j], which is exactly what you want to do.