When using lamdba a few days ago, this error was reported because a variable was used in the body of lamdba. I think it’s very strange
Today, when I read this book, I saw this explanation again. Here I have a deeper understanding. To sum up:
Before JDK1.8, when using anonymous inner classes, variables in methods must be added with final
Otherwise, an error will be reported. However, JDK1.8 has relaxed this restriction and can use non final modification. However, this variable is not allowed to be assigned another value. Otherwise, the weight of lamdba will also report an error, as shown in the figure
in other words, lambda expressions refer to values, not variables. Therefore, the use of variables in lambba and anonymous inner classes cannot be changed
If you try to assign a value to the variable many times, and then refer to it in a lambda expression, the compiler will report an error. A typical example is to use lamdba in the for loop. If you need to use the I variable of the for loop, then lamdba is not appropriate