The enhanced for statement introduced in Java 1.5, commonly referred to as the for-each idiom, is primarily used for iterating over collections of objects. While similar to the for statement, assignments to the loop variable do not modify the collection of objects over which the loop iterates. Assignments to the loop variable may not have the effect intended by the developer and should be avoided.
In more detail, according to the JLS an enhanced for statement of the form:
| Code Block |
|---|
for (ObjType obj : someIterableItem) {
...
}
|
is designed for iteration through Collections and arrays.
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 or the iterated collection or array. ConsequentlyTherefore, an assignment to the loop variable is equivalent to modifying a variable local to the loop body whose initial value is the collection item referred to object referenced by the loop iterator. While this This modification is not necessarily erroneous , it may but can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for statement.
It is recommended that Declare all enhanced for statement loop variables be declared final. The final declaration will cause the causes Java compiler compilers to flag and reject any assignments made to the loop variable in the loop body.
Noncompliant Code Example
This noncompliant code example attempts to initialize a Character array process a collection of integers using an enhanced for loop. However, because assignments to the loop variable to not modify the collection or array over which the loop is iterating, the array is not suitably initialized.It further intends to modify one item in the collection for processing:
| Code Block | |||||
|---|---|---|---|---|---|
| |||||
List<Integer> list Character[] array = Arrays.asList(new CharacterInteger[10]] {13, 14, 15}); boolean first = true; System.out.println("Processing list..."); for (CharacterInteger c: arrayi: list) { if (first) { c first = 'x'false; // initialization attempt for(int i=0;i<array.length;i++) = new Integer(99); } System.out.print(array[i]);println(" New item: " + i); // prints 10 "null"s |
Note that if c was declared final in the noncompliant code example the Java compiler would issue a compilation error regarding the "c = 'x'; statement.
Compliant Solution
This compliant solution correctly initializes the array using a for loop.
Process i
}
System.out.println("Modified list?");
for (Integer i: list) {
System.out.println("List item: " + i);
}
|
However, this code does not actually modify the list, as shown by the program's output:
Processing list...
New item: 99
New item: 14
New item: 15
Modified list?
List item: 13
List item: 14
List item: 15
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) {
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:
| Code Block | ||||
|---|---|---|---|---|
| ||||
// ...
for (final Integer i: list) {
Integer item = i;
if (first) {
first = false;
item = new Integer(99);
} | ||||
| Code Block | ||||
| ||||
Character[] array = new Character[10]; for(int i=0;i<array.length;i++) array[i] = 'x'; for(final Character c: array) System.out.print(cprintln(" New item: " + item); // prints 10 "x"s Process item } // ... |
Risk Assessment
Attempts Assignments to assign to the loop variable from within the of an enhanced for loop (for-each idiom) are futile and may leave the class 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
...
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
TODO
References
| Wiki Markup |
|---|
\[[JLS 05|AA. Java References#JLS 05]\] Section [14.14.2|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] "The enhanced for statement" |
| Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Klocwork |
| JD.UNMOD | |||||||
| Parasoft Jtest |
| CERT.DCL02.ITMOD | Do not modify collection while iterating over it |
Bibliography
...
DCL08-J. Enforce compile-time type checking of variable argument types 02. Declarations and Initialization (DCL) DCL31-J. Qualify mathematical constants with the static and final modifiers