2

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?

Peter
  • 1,381
  • 2
  • 13
  • 24

3 Answers3

4

The assigment

obj = new MyObject();

just set a new object in the variable obj, and does not change the value in the array, it only changes the reference variable obj.

What happens is that objects[i][j] is assined to obj, and then you change the value of obj, without changing the actual array.

when you assign directly to objects[i][j] - it works as expected, since you change the value of objects[i][j], which is exactly what you want to do.

amit
  • 175,853
  • 27
  • 231
  • 333
3

References are passed by value, so obj = new MyObject(); only updates the local copy of your reference to objects[i][j].

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
1

It only works for the outer loop, because there are new references being made, but not deep ones:

public static void main (String[] args ) {
    Integer [][] iaa = new Integer[3][4];
    for (Integer[] ia : iaa) {
        for (int i = 0; i < ia.length; ++i) {
            ia[i] = i; 
        }
    }
}
user unknown
  • 35,537
  • 11
  • 75
  • 121