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

...

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.

Noncompliant Code Example

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:

...

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 code exampleproblem, by causing the compiler to fail to permit i to be assigned a new value.

Code Block
bgColor#ffcccc
langjava
// ...
for (final Integer i: list) {

// ...

Compliant Solution

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
}

 
// ...

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

This rule is easily enforced with static analysis.

Bibliography

...