Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't array elements initialized in an enhanced for loop?

When I use normal for-loop,
all elements in an array will initialize normally:

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


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

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


I thought obj refers to a particular element in an array,
so if I initialize it, the array element will be initialized as well.
Why isn't that happening?

like image 918
SmRndGuy Avatar asked Oct 19 '13 08:10

SmRndGuy


People also ask

Can you use enhanced for loop on array?

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.

What happens if an array element is not initialized?

If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. The same applies to elements of arrays with static storage duration. (All file-scope variables and function-scope variables declared with the static keyword have static storage duration.)

How do you declare an array in a for loop?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.


1 Answers

I thought obj refers to a particular element in an array, so if I initialize it, the array element will be initialized as well. Why isn't that happening?

No, obj has the value of the array element at the start of the body of the loop. It isn't an alias for the array element variable. So a loop like this (for arrays; it's different for iterables):

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

Is equivalent to:

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

See section 14.14.2 of the JLS for more details of the exact behaviour of the enhanced for loop.

like image 118
Jon Skeet Avatar answered Sep 30 '22 12:09

Jon Skeet