在foreach循环中具有最终变量的工作方式

考虑这段代码

public static void main(String[] args) {
    for(final String s : Arrays.asList("a","b","c")){
        System.out.println(s);
    }
}

This code doesn't serve a specific purpose but to demonstrate the usage of final foreach-loop variables.

How does this work ? How can a single variable be final yet it is assigned a different value with each loop. Or is this variable declared multiple times in different scopes\stacks ?

评论
  • 吐泡泡oo
    吐泡泡oo 回复

    This is explained in the Java Language Specification (JLS), 14.14.2:

    The enhanced for statement has the form:

    EnhancedForStatement:
        for ( FormalParameter : Expression ) Statement
    
    FormalParameter:
        VariableModifiers_opt Type VariableDeclaratorId
    
    VariableDeclaratorId:
        Identifier
        VariableDeclaratorId []
    

    ...

    The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
        VariableModifiers_opt TargetType Identifier =
            (TargetType) #i.next();
        Statement
    }
    

    Thus, the Identifier is redeclared on each iteration of the loop.

  • 99.90%
    99.90% 回复

    The main idea behind allowing final in that context is to let you use the loop variable in an anonymous class. Other than that, final does not change the semantic of the loop variable s: it goes through the elements of the collection in the same way as usual.

    Another effect of using final is that you are no longer allowed to assign a new value to s. This is generally a bad idea, although the compiler lets you do it.

  • fearum
    fearum 回复

    这只是意味着您无法在设置对象引用后对其进行修改。因此,在这种情况下,“最终”仅适用于每次迭代。 :D