在for循环中使用final变量的目的是什么? [英] What is the purpose of using final for the loop variable in enhanced for loop?
问题描述
for(final动物动物:animalList){
//做一些功能
}
但是在这里使用final关键字的目的是什么? / b>
有两种可能的原因:
-
它可以简单地避免在循环体中意外地改变循环变量。 (或者 document 这个循环变量不会被改变的事实)。
-
可以这样做,可以引用匿名内部类中的循环变量。例如:
$ b $ pre $for(final动物动物:animalList){
executor.submit(new Runnable(){
public void run(){
animal.feed();
}
});
$ b $ p
$ b这是一个编译错误,如果省略
最后
在这个例子中。
更新这不是Java 8及更高版本中的编译错误。非局部变量现在只需要有效地终结。简而言之,这意味着在初始声明/初始化之后,该变量没有被分配给(使用赋值操作符或前/后增加或减少运算符)。
I understand how the below statement works.
for(final Animal animal : animalList){
//do some function
}
But what is the purpose of using the final keyword here ?
There are two possible reasons to do this:
It could simply be a way to avoid changing the loop variable accidentally in the loop body. (Or to document the fact that the loop variable is not going to be changed.)
It could be done so that you can refer to the loop variable in an anonymous inner class. For example:
for(final Animal animal : animalList){ executor.submit(new Runnable(){ public void run() { animal.feed(); } }); }
It is a compilation error if you leave out the
final
in this example.UPDATE it is not a compilation error in Java 8 and later versions. The non-local variable is now only required to be effectively final. In simple terms, that means that the variable is not assigned to (using an assignment operator or a pre/post increment or decrement operator) after the initial declaration / initialization.
这篇关于在for循环中使用final变量的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!