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?
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.
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.)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With