What is the purpose of using final for the loop va

2019-04-18 05:44发布

问题:

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 ?

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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



回答5:

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.