Why are array elements not initialized in an extended loop?

When I use the usual for loop, all elements in the array will be initialized normally:

Object[] objs = new Object[10]; for (int i=0;i<objs.length;i++) objs[i] = new Object(); 


But when I use the for-each loop. The elements of the array are still null , after the loop:

 Object[] objs = new Object[10]; for (Object obj : objs) obj = new Object(); 


I thought obj refers to a specific element in the array, So if I initialize it, the array element will also be initialized.
Why is this not happening?

+6
source share
4 answers

I thought obj refers to a specific element in the array, so if I initialize it, the array element will also be initialized. Why is this not happening?

No, obj has the value of an array element at the beginning of the loop body. It is not an alias for an array element variable. So, such a loop (for arrays, it differs for iterations):

 for (Object obj : objs) { // Code using obj here } 

It is equivalent to:

 for (int i = 0; i < objs.length; i++) { Object obj = objs[i]; // Code using obj here } 

See JLS Section 14.14.2 for more details on the exact behavior of the extended loop.

+10
source
 Object[] objs = new Object[10]; for (Object obj : objs) obj = new Object(); 

You created space where the objects will go, but you have not actually created the objects. This will try to iterate over the objects in the array if they exist (which they haven't done yet!)

 Object[] objs = new Object[10]; for (int i=0; i < objs.length; i++) objs[i] = new Object(); 

This is different in that you simply count from 0 to 9 and create + save them in the appropriate place in the array.

+1
source

You assign a new value to "obj", not "objs", so the elements are null. You must also assign a value to the objects:

  Object[] objs = new Object[10]; for (int k = 0; k < objs.length; k++) { objs[k] = new Object(); System.out.println(objs[k]); } 
0
source

You assign a new object to an array element (which is a variable that will be a reference to the object), which can be accessed outside the for loop.

 Object[] objs = new Object[10]; for (int i=0;i<objs.length;i++) objs[i] = new Object(); 

But for each loop, you assign a new object to a local variable (and not to the elements of the array)

 Object[] objs = new Object[10]; for (Object obj : objs){ obj = new Object(); } //obj can not be accessed here 

and if we talk about this line

  for (Object obj : objs){ 

Then this means that you take the value of the objs element into the local variable obj, which is null.

0
source

Source: https://habr.com/ru/post/956305/


All Articles