Cosider this code:
for (int value : values) {
values[value] = -values[value] - 1;
}
Is it guaranteed to pick updated values when the iteration process reaches appropriate elements?
Experimentally I figured ut that it works as expected (iteration yields the updated values).
Also from Java spec I can conclude that it should work:
The enhanced for statement is equivalent to a basic for statement of the form:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
{VariableModifier} TargetType Identifier =
(TargetType) #i.next();
Statement
}
I just wonder, if there is an 'official' confirmation that it's valid and guaranteed to pick the updated values?
Update: Excluded according to comments:
I am in doubt because analogous code would be invalid for e.g.
ArrayList.
List<Integer> values = new ArrayList<>(Arrays.asList(6, 5, 3, 2, 2, 4, 0, 1)); for (int value : values) { values.set(value, values.get(value) + 1); }works perfectly fine. You obviously can't use[]on a List, but that's unrelated to the enhanced for loop.The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.Apparently,ArrayList#setis not astructural modification, and so my analogy was admittedly wrong: one cannot structurally modify a Java array.