我不了解lambda的一些事情.
String s = "Hello World";
Function<Integer, String> f = s::substring;
s = null;
System.out.println(f.apply(5));
Run Code Online (Sandbox Code Playgroud)
为什么该f.apply方法仍然有效s = null.毕竟,StringGC应该删除该对象,因为没有指向该对象的指针.
还有一件事,为什么我不需要这里的退货声明?
Function<Integer, String> f = t -> t + "";
Run Code Online (Sandbox Code Playgroud) NullPointerException当我使用方法引用绑定到dog后来分配null给变量的变量时,为什么代码没有抛出?
我正在使用Java 8。
import java.util.function.Function;
class Dog {
private int food = 10;
public int eat(int num) {
System.out.println("eat " + num);
this.food -= num;
return this.food;
}
}
public class MethodRefrenceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
Function<Integer, Integer> function = dog::eat;
dog = null;
// I can still use the method reference
System.out.println("still have " + function.apply(2));
}
}
Run Code Online (Sandbox Code Playgroud)