I was reading some code found on the web and fell on these lines (java):
private List<String> values;
[...开发者_StackOverflow]
for (final String str : values) {
length += context.strlen(str);
}
What is the advantage of declaring a variable final in a for loop ? I thought the variable specified in the for loop was already read-only (e.g. can't assign something to 'str' in the above example).
Thx
What is the advantage of declaring a variable final in a for loop ?
Not much in a small piece of code, but, if it would help to avoid changing the reference while looping.
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 );
}
If you don't use final, the last line anotherComputation
can potentially use a different value than the one was defined in the iteration and subtle bugs may be introduced, while reading other code the maintainer will try to figure out how come that method is failing with the correct values.
For a 5 - 15 lines long for this is easy to spot, but for larger segments of code, believe me, is much harder.
Using final
will prevent value change at compile time.
...
for( final String s : values ) {
s = new StringBuilder( s ).reverse().toString();
}
This code fails at compile time variable s might already have been assigned
Another advantage could be to allow the variable to be used inside an anonymous inner class:
for( final String s : value ) {
doSomething( new InnerClass() {
void something() {
s.length();// accesing s from within the inner class
}
});
}
Declaring a loop variable as final is a purely stylistic thing:
You protect yourself from accidentally adding a statement to the loop body that changes the loop variable.
You make it clear to someone else reading the code that the loop variable won't change in the loop body.
I personally don't think this is a big thing. But that's because I'd never write code that does this ... without adding a big bold comment to explain what was going on, and why I'd decided to do it that way. (But I can see the point if you are in environment where such abominations are commonplace ...)
I thought the variable specified in the for loop was already read-only (e.g. can't assign something to 'str' in the above example).
Nope. A for loop variable (provided it is not declared as final
) can be modified in the body of the loop.
If you want to read the nitty-gritty details, the for loop is described in the JLS section 14.14. It does not explicitly mention loop variables declared as final
. But the general picture is that the only difference between a loop variable defined declared in the for
statement and any other variable is the scoping.
I thought the variable specified in the for loop was already read-only
It's not read-only, try it.
Some people like declaring local variables 'final', not sure why. And looks like this is such case.
In any case, don't consider arbitrary code sample you found on the web to be style model.
It may sometimes be helpful to declare it as final in the case that this variable is used by creating an annonymous class.
For example:
String[] names = {"my name"};
for(final String name: names){
new Object(){
String objName = name;
};
}
No, its not read only. Its a temporary variable that has the scope of the loop.
By adding the final
keyword, you are making it read only.
$ 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
$
精彩评论