What is the purpose of using final for the loop va

2019-04-18 06:11发布

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 ?

5条回答
劳资没心,怎么记你
2楼-- · 2019-04-18 06:23

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.

查看更多
淡お忘
3楼-- · 2019-04-18 06:32

It's another java best practise.

The final declaration causes Java compilers to reject any assignments made to the loop variable.

When ever you have a chance, Declare all enhanced for statement loop variables final

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-18 06:35

The code is a syntax sugar for this equivalent code:

for (final Iterator<Animal> iterator = animals.iterator(); iterator.hasNext(); ) {
  final Animal animal = iterator.next();

}

I think it is answers the question.

查看更多
萌系小妹纸
5楼-- · 2019-04-18 06:40

It simply means that the value of animal cannot change once it is set by the for loop. This may be required if you're going to reference animal within an anonymous class at some point in the loop.

Even if it isn't explicitly needed, it is good practice to make variables that will not change final. It can help you catch mistakes, and makes the code more self-documenting.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-04-18 06:48

Adding final keyword makes no performance difference here. It's just needed to be sure it is not reassigned in the loop.

To avoid this situation which can lead to confusions.

 for(Animal animal : animalList){
       //do some function
       animal = anotherAnimal;
       // use animal variable here
    }

You could also need to use this variable in anonymous function inside the loop

查看更多
登录 后发表回答