The enhanced for
statement is designed for iteration through Collections and arrays.
The Java The Java Language Specification (JLS) provides the following example of the enhanced for
statement in §14.14.2, "The Enhanced for
Statement" [JLS 2014]:
...
Declare all enhanced for
statement loop variables final. The final
declaration causes Java compilers to flag and reject any assignments made to the loop variable.
...
This noncompliant code example attempts to process a collection of integers using an enhanced for
loop. It further intends to modify one item in the collection for processing:
Code Block | ||||
---|---|---|---|---|
| ||||
List<Integer> list = Arrays.asList(new Integer[] {13, 14, 15}); boolean first = true; System.out.println("Processing list..."); for (Integer i: list) { if (first) { first = false; i = new Integer(99); } System.out.println(" New item: " + i); // processProcess i } System.out.println("Modified list?"); for (Integer i: list) { System.out.println("List item: " + i); } |
...
Compliant Solution
Declaring i
to be final mitigates this problem by causing the compiler to fail to permit i
to be assigned a new value.:
Code Block | ||||
---|---|---|---|---|
| ||||
// ... for (final Integer i: list) { // ... |
...
Code Block | ||||
---|---|---|---|---|
| ||||
// ... for (final Integer i: list) { Integer item = i; if (first) { first = false; item = new Integer(99); } System.out.println(" New item: " + item); // processProcess item } // ... |
Risk Assessment
Assignments to the loop variable of an enhanced for
loop (for-each
idiom) fail to affect the overall iteration order, lead to programmer confusion, and can leave data in a fragile or inconsistent state.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL02-J | Low | Unlikely | Low | P3 | L3 |
Automated Detection
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.DCL02.ITMOD | Do not modify collection while iterating over it |
Bibliography
...
...