The enhanced for
statement introduced in Java 1.5, commonly referred to as the for-each idiom, finds primary application in is primarily used for iterating over collections of objects. While similar to the usual for
statement, this idiom cannot be used to assign values to the loop variable.
Noncompliant Code Example
The intention behind this This noncompliant example is attempts to initialize a Character
array using an enhanced for
loop. However, because the loop variable cannot be assigned to, the array is not suitably initialized.
...
Attempts to assign to the loop variable from within the enhanced for
loop (for-each idiom) will be are futile and may leave the class in a fragile, inconsistent state.
...