For each loop, it is not possible to initialize objects in an array

I will quickly move on to the problem. I have a simple class

class Vector{ float x, y; } 

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

 Vector[] buffer; 

I initialize it as follows:

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

but when I try to access the elements of this object in this array, I get a NullPointerException directly to my stack trace. That is, array objects were not built. On the other hand, this more traditional code works just fine:

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

As this one discusses this, both should be the same after compilation.

My question is: why for each cycle it is not possible to initialize / build objects from an array of elements?

+8
java syntax for-loop
source share
3 answers

In your example, for each example, you are rewriting a local loop variable that does not return to the array. It looks like your second loop:

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

Check out Understanding for Each Cycle in Java for basically the same issue.

+5
source share

Both loops are the same for accessing elements from an array, but not for their initialization. When you use the for-each loop in this script, he likes to do

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

You do not assign a new Vector to the array; instead, you assign it to a local variable.

+5
source share

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

+2
source share

All Articles