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?
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.
See more on this question at Stackoverflow