Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The enhanced for statement is designed for iteration through Collections and arrays

The The Java Language Specification (JLS) provides the following example of the enhanced for statement in §14.14.2, "The Enhanced for Statement" [JLS 2014]:

...

Unlike the basic for statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. 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.

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.

...

Code Block
bgColor#ffcccc
langjava
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);
  // 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:

...

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.

...

This compliant solution processes the '"modified' " list , but leaves the actual list unchanged.:

Code Block
bgColor#ccccff
langjava
// ...
 
for (final Integer i: list) {
  Integer item = i;
  if (first) {
    first = false;
    item = new Integer(99);
  }
  System.out.println(" New item: " + item);
  // process item
}

// ...

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL02-J

lowLow

unlikelyUnlikely

lowLow

P3

L3

Automated Detection

This rule is easily enforced with static analysis.

...