Example code:
int a[] = new int[]{0, 1, 2, 3};
int result = 0;
for (int i : a)
result += i;
Is the loop guaranteed to iterate across a[0]
, a[1]
, a[2]
, a[3]
in that order? I strongly believe the answer is yes, but this page seems to not unambiguously state order.
Got a solid reference?
According to the JLS, The enhanced
for
statement, your for-loop is equivalent to"where
array
andindex
are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhancedfor
statement occurs." (slightly paraphrasing the variable names here).So yes: the order is absolutely guaranteed.
It states in the JLS that:
is equivalent to
See section 14.14.2 of the Java Language Specification, 3rd edition.
I did not find anything in the page you've referenced that would imply out-of-order iteration. Can you post the specific quote?
In any case, I find that this code:
decompiles to old-style looping:
Of course, that's not the same as a guarantee, but at the very least out-of-order iteration over an array would be very weird and would seem to go against obvious common-sense implementation.