Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for each loop cannot initialize objects in array [duplicate]

I will dive quick to the problem. I have a straightforward class

class Vector{
    float x, y;
}

and another class has an array of these objects as its member

Vector[] buffer;

I initialize it like this:

buffer = new Vector[8];
for(Vector v: buffer)
    v = new Vector();

but when I try to access this objects' members in this array I get a NullPointerException straight to my stack trace. That is, objects of array have not been constructed. On the other hand this more traditional code works just perfect:

buffer = new Vector[8];
for(int i = 0; i<8; i++)
    buffer[i] = new Vector;

As this discussion points it out, both should be the same after compilation.

My question is, why for each loop fails to initialize/construct objects from the item array?

like image 895
mehmetminanc Avatar asked Sep 04 '12 01:09

mehmetminanc


3 Answers

In your for-each example you are overwriting the local variable of the loop which does not get saved back into the array. It is similar to in your second loop going:

for(int i = 0; i < buffer.length; i++){
    Vector v = buffer[i];
    v = new Vector();
}

Check out Understanding for each loop in Java for basically the same issue.

like image 198
n00begon Avatar answered Nov 09 '22 05:11

n00begon


Both loops are the same for accessing elements from an array, but not for initializing them. When you use a for-each loop in this scenario, it's like doing

for(int x = 0; x < array.length; x++) {
    Vector v = array[x];
    v = new Vector();
}

You are not assigning the new Vector to the array, instead you are assigning it to a local variable.

like image 25
Jeffrey Avatar answered Nov 09 '22 06:11

Jeffrey


In your first example, v is available only inside the for loop. When you do v = new Vector(); v is updated, but not buffer[i]. v was pointing to buffer[i] before, now it points to a new vector, buffer[i] remains as null.

like image 2
fastcodejava Avatar answered Nov 09 '22 04:11

fastcodejava