我正在阅读网上发现的一些代码,并在这些行上(java):
private List<String> values;
[...]
for (final String str : values) {
length += context.strlen(str);
}
Run Code Online (Sandbox Code Playgroud)
在for循环中声明变量final有什么好处?我认为for循环中指定的变量已经是只读的(例如,在上面的例子中不能为'str'赋值).
谢谢
在for循环中声明变量final有什么好处?
在一小段代码中并不多,但是,如果它有助于避免在循环时更改引用.
例如:
for( String s : values ) {
computeSomething( s );
... a dozen of lines here...
s = s.trim();// or worst s = getOtherString();
... another dozen of line
otherComputation( s );
}
Run Code Online (Sandbox Code Playgroud)
如果你不使用final,最后一行anotherComputation可能会使用与迭代中定义的值不同的值,并且可能会引入细微的bug,而在阅读其他代码时,维护者将尝试弄清楚该方法如何失败正确的价值观.
对于5到15行的长度来说这很容易被发现,但对于更大的代码段,相信我,要困难得多.
使用final将防止在编译时更改值.
...
for( final String s : values ) {
s = new StringBuilder( s ).reverse().toString();
}
Run Code Online (Sandbox Code Playgroud)
此代码在编译时失败 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
}
});
}
Run Code Online (Sandbox Code Playgroud)