문제

Consider this piece of code

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 ?

도움이 되었습니까?

해결책

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.

다른 팁

It simply means you cannot modify the object reference after it has been set. So in this case, "final" applies only within each iteration. :D

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top