当前位置:网站首页>Variable used in lambda expression should be final or effectively final

Variable used in lambda expression should be final or effectively final

2020-11-10 16:03:01 Sister Hong Kong Island

Use JAVA8 When operating on a set , Tips Variable used in lambda expression should be final or effectively final

The meaning of this sentence is :lambda The variable used in the expression should be final Or effective final

Actually in Java 8 Before :

 If you want to access local variables in an anonymous class , That local variable must be explicitly declared as  final

We know :

lambda Expressions are evolved from anonymous inner classes , Their role is to implement interface methods , So the analogy is anonymous inner class ,lambda The variables used in expressions also need to be final type .

take BorrowerSet Assign to another Set You can compile ;

What then? finalBorrowerSet It's not a statement final What about the type? ?

Because :

Java 8 after , In the anonymous class or Lambda Local variables accessed in expressions , If not final Type words , The compiler automatically adds final Modifier .

Why? lambda Expressions or anonymous inner classes cannot access non final Local variables of , Why? ?

         In fact, this is about Jvm Memory models and threads , Because instance variables are in the heap , Local variables are allocated on the stack ,lambda expression ( Anonymous inner class ) It will be executed in another thread . If you want to access a local variable directly in a thread , Maybe the local variable has been destroyed when the thread executes , and final The local variable of type is in Lambda expression ( An anonymous class ) Is actually a copy of a local variable .

 

版权声明
本文为[Sister Hong Kong Island]所创,转载请带上原文链接,感谢