Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: done

The enhanced for statement introduced in Java V1. 5 (also known as the for-each idiom) is primarily used for iterating over collections of objects. Unlike the original for statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. Consequently, assignments to the loop variable can have an effect other than what is intended by the developer. This provides yet another reason to avoid assigning to the loop variable in a for loop.

...

The attempt to skip to the next item is "successful" appears to succeed because the assignment is successful, and the value of processMe is updated. Unlike an original for loop, however, the assignment leaves the overall iteration order of the loop unchanged. As a result, the object following the skipped object is processed twice; this is unlikely to be what the programmer intended.

Note that if processMe were declared final, a compiler error would result at the attempted assignment.

...

This compliant solution correctly processes the objects in the collection not no more than one time.

Code Block
bgColor#ccccff
Collection<ProcessObj> processThese = // ... 

for (final ProcessObj processMe: processThese) {
  if (someCondition) { // found the item to skip
    someCondition = false;
    continue; // skip by continuing to next iteration
  }
  processMe.doTheProcessing(); // process the object
}

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="463fb5ed69985ced-5f841655-483f4537-b607a738-d9e484da627f8e842220acf8"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§14.14.2,"The enhanced for statement"

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2]

]]></ac:plain-text-body></ac:structured-macro>

...