Is it possible to initialise an array in Java using the 'advanced' for loop?
e.g.
Integer[ ] numbers = new Integer[20];
int counter = 0;
for ( Integer i : numbers )
{
i = counter++;
}
for ( Integer i : numbers )
{
System.out.println(i);
}
This prints all nulls, why is that?
No, because you aren't assigning to the array, you are assigning to the temporary variable called i
. The array doesn't see the change.
The following shows roughly equivalent code using the normal for
loop. This should make it easier to see why it fails to update the array:
for (int j = 0; j < numbers.length; j++) {
Integer i = arr[j]; // i is null here.
i = counter++; // Assigns to i. Does not assign to the array.
}
The reason why you get null values as output is that you do not store any values in the array.
You can use the foreach loop to initialize the array, but then you must manually maintain a counter to reference the array elements:
for (Integer i : numbers ){
numbers[counter] = counter;
counter++;
}
Clearly, this is not the intended use case for the foreach loop. To solve your problem, I would suggest using the "traditional" for loop:
for (int i = 0; i < numbers.length; i++){
numbers[i] = i;
}
Note, it is possible to fill all elements with the same value using Arrays.fill(int[] array, int val).
Basically no, not as you wish. In the 'advanced' for loop, there is no way to access the hidden counter, and neither is there to perform a write access on the corresponding array slot.
The 'advanced' for-loop doesn't expose the counter to you, and hence, you cannot write the result of counter++
to the specific array slot.
Your case is the case where the 'advanced' for-loop isn't made for. See:
http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html
Take a look at the last paragraph.
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