注意:这个问题源于一个死链接,这是以前的SO问题,但是这里......
看到这个代码(注意:我不知道,这个代码将不能"工作",而Integer::compare应使用-我只是提取它从链接的问题):
final ArrayList <Integer> list
= IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
System.out.println(list.stream().max(Integer::max).get());
System.out.println(list.stream().min(Integer::min).get());
Run Code Online (Sandbox Code Playgroud)
据javadoc的.min()和.max(),两者的参数应该是一个Comparator.然而,这里的方法引用是Integer类的静态方法.
那么,为什么要编译呢?
我很难理解为什么以下代码编译:
public class MethodRefs {
public static void main(String[] args) {
Function<MethodRefs, String> f;
f = MethodRefs::getValueStatic;
f = MethodRefs::getValue;
}
public static String getValueStatic(MethodRefs smt) {
return smt.getValue();
}
public String getValue() {
return "4";
}
}
Run Code Online (Sandbox Code Playgroud)
我可以看到为什么第一个赋值是有效的 - getValueStatic显然匹配指定的Function类型(它接受一个MethodRefs对象并返回一个String),但第二个让我感到困惑 - 该getValue方法不接受任何参数,那么为什么它仍然有效分配给它f?