Final keyword in for

I read some code found on the Internet and fell into these lines (java):

private List<String> values;

[...]

for (final String str : values) {
   length += context.strlen(str);
}

What is the advantage of declaring a final variable in a for loop? I thought that the variable specified in the for loop was already read-only (for example, it could not assign something to “str” in the above example).

thank

+3
source share
5 answers

What is the advantage of declaring a final variable in a for loop?

Not so much in a small piece of code, but if this helps to avoid changing the link during the loop.

For instance:

for( String s : values ) {
     computeSomething( s );
      ... a dozen of lines here... 
     s = s.trim();// or worst s = getOtherString();
     ... another dozen of line 
     otherComputation( s );
 }

final, anotherComputation , , , , , .

5 - 15 , , , .

final .

... 
for( final String s : values ) {
  s = new StringBuilder( s ).reverse().toString();
}

variable s might already have been assigned

, :

for( final String s : value ) {
    doSomething( new InnerClass() {
       void something() {
             s.length();// accesing s from within the inner class 
       }
    });
 }
+5

final :

  • , .

  • -, , .

, . , , ... , , , . ( , , ...)

, , for, (, - "str" ).

. A ( ​​ final) .

, for JLS 14.14. , final. , , for , - .

+2

, , for, , .

"final", , . , .

, , , .

+1

, . , .

final, .

$ cat Finals.java
import java.util.List;


public class Finals {

    public static void main(String args[]){

        int ints[] = {1,2,3,4};

        for (Integer i:ints){
            i +=20;
            System.out.println(i);
        }    
    }    
}
$ javac Finals.java -cp .
$ java Finals
21
22
23
24
$ 
0

, .

:

    String[] names = {"my name"};
    for(final String name: names){
        new Object(){
            String objName = name;
        };
    }
0
source

Source: https://habr.com/ru/post/1756844/


All Articles