...
The Java Language Specification (JLS) provides the following example of the enhanced for statement in §14.14.2, "The Enhanced for Statement" [JLS 2014]:
The enhanced for statement is equivalent to a basic for statement of the form:
Code Block for (I #i = Expression.iterator(); #i.hasNext(); ) { {VariableModifier} TargetType Identifier = (TargetType) #i.next(); Statement }#i is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope...at the point where the enhanced for statement occurs.
Unlike the basic for statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objectsor the iterated collection or array. Consequently, an assignment to the loop variable is equivalent to modifying a variable local to the loop body whose initial value is the object referenced by the loop iterator. This modification is not necessarily erroneous but can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for statement.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
// ... for (final Integer i: list) { if (first) { first = false; i = new Integer(99); // compiler error: variable i might already have been assigned } // ... |
Compliant Solution
This compliant solution processes the "modified" list but leaves the actual list unchanged:
...
Assignments to the loop variable of an enhanced for loop (for-each idiom) fail to affect the overall iteration order , or the iterated collection or array. This can lead to programmer confusion, and can leave data in a fragile or inconsistent state.
Rule | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level |
|---|---|---|
DCL02-J | Low | Unlikely |
Yes | No |
P2 | L3 |
Automated Detection
| Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Klocwork |
| JD.UNMOD | |||||||
| Parasoft Jtest |
| CERT.DCL02.ITMOD | Do not modify collection while iterating over it |
Bibliography
...
...