The enhanced for statement 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:

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 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.

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:

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:

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:

// ...
for (final Integer i: list) {

// ...

Compliant Solution

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

// ...
 
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

ToolVersionCheckerDescription
Parasoft Jtest
2023.1
CERT.DCL02.ITMODDo not modify collection while iterating over it

Bibliography



11 Comments

  1. In playing with the NCCE I found out something interesting. First, declaring the loop variable c in the enhanced for statement as final makes the compiler reject the NCCE with the error 'variable c might already have been assigned'.

    Second, modifying the NCCE so that the enhanced loop variable is final and not modified in the loop body compiles cleanly. The program behaves as expected:

    class test {
        
        public static void main(String args[]) {
    
            Character[] array = new Character[10];
            for(int i=0;i&lt;array.length;i++) 
                array[i] = ((char) (65+i));
    
            for(final Character c: array) 
                System.out.println(c);
        }
    
    }
    

    This prints out:

    A
    B
    C
    D
    E
    F
    G
    H
    I
    J
    

    This raises the possibility of suggesting that all loop variables in an enhanced for loop be declared final, which would then allow the Java compiler to flag any cases where the loop variable is modified in the loop. (I'm not sure why the compiler allows the loop variable to be declared as final since its value changes on each loop iteration, anyone have any ideas?).

    I will investigate this further.

    1. Poking around on the web yielded this information (http://jimmenard.blogspot.com/2006/12/javas-enhanced-for-loop-mystery.html):

      I think the syntax 'for (Foo foo : bar) { doStuff(); }', 
      where bar is iterable, is a simple macro for the following code:
      
      for (Iterator myIterator = bar.iterator(); iterator.hasNext();)
      {
      Foo foo = myIterator.next();
      }
      

      So, declaring the loop variable as final in the above example would give you:

      for (final Foo foo : bar) { doStuff(); }
      
      Is implemented as:
      
      for (Iterator myIterator = bar.iterator(); iterator.hasNext();)
      {
      final Foo foo = myIterator.next();
      }
      

      This explains the behavior I am seeing in my example program.

      Does always declaring the loop variable as final sound like a good recommendation?

      1. I think it should prevent inadvertent modification. It can be included as a CS. Good find!
        Can you edit your comment and reduce the length of the code/comment in the {code} section so that the page displays properly? Thanks.

  2. Note that we replaced the example. The new code emphasizes the effects on iteration rather than the object-ref vs. array-index-ref from the previous example.

  3. While I like the fact that the NCE/CS demonstrate the problem, there are some things to think about:

    • processMe is an object and at that abstraction having a getNext() seems a bit questionable, unless processMe is something like a linked list object. Assuming it is, the NCE and CS become confused (what would someone achieve by writing such code). Can you suggest a real Java object that can be used in the place of "processMe"?
    • To do something like this, especially in the presence of a Collection, an iterator would be used instead of a for-each loop. Maybe we need a guideline warning about mixing an iterator with for-each.
    • I'm unsure that this problem is noteworthy enough to deserve mention in the upcoming target release.
    1. I agree with Dhruv's comments here.  I wrote the following NCE which fails with a java.util.ConcurrentModificationException

              List<String> myList = new ArrayList<String>();
              Iterator<String> i = myList.iterator();
              myList.add("Java");
              myList.add(null);
              myList.add("C");
              myList.add("C++");
              
              for (String s : myList) {
                  if (s == null) { // skip null items
                      s = i.next(); // attempt to skip to next item
                  }
                  System.out.println(s); // print the String
              }

      I would like to see a realistic example where "the object following the skipped object is processed twice."

  4. I can't find this quote in any version of the JLS, including the 3rd edition:

    As detailed in the JLS, §14.14.2, "The Enhanced For Statement" [JLS 2005]:

    An enhanced for statement of the form

     

    for (ObjType obj : someIterableItem) {
      // ...
    }

     

    is equivalent to a basic for loop of the form

    for (Iterator myIterator = someIterableItem.iterator(); myIterator.hasNext();) {
      ObjType obj = myIterator.next();
      // ...
    }
    1. I found the quote, it has mutated a good bit.

    1. Well, the link is er...frayed, not broken. Confluence does link to the right page (with modified title).

  5. As i read the description of the rule Parasoft JTest BD.CO.ITMOD-1, i dont think it is a good coverage avec this Rule.

    I understand that the tool check if list is modified other than through the iterator.

    It not aim on list's objets them self.