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?

2
  • 2
    Related : stackoverflow.com/q/2556419/1140748 Commented Apr 28, 2012 at 10:06
  • @alain.janinm: Don't close, because the other question only handles simple Arrays, not nested Arrays. You can initialise the outer Array that way - see my answer below. Commented Apr 28, 2012 at 10:36

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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; 
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.