Why do lambda expressions in Java 8 need to use variables to use the “final” modifier instead of using method references?

Consider the following courses:

class Foo<T> {

    void handle(T t) {
        System.out.println("handling " + t);
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);

        Foo<Integer> f = new Foo<>();

        list.forEach(f::handle);             // compiles fine
        //list.forEach(obj -> f.handle(obj));// compilation error

        f = new Foo<>(); // reassign f

    }
}@H_301_3@ 
 

为什么我得到obj的编译错误 – > f.handle(obj),但不适用于f :: handle?

Solution

These two different structures are doing two different things In the first case, you will get the method reference of a specific object: this only needs to be executed once, and then the JVM has its own reference (so effectively eventually) to the object F and can call the handle method In the second case, the JVM must resolve the f reference at each call, so it complains that f must be final You can easily write code that sets f to null while foreach is running, resulting in NPE

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>