代码如下
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("hello");
list.add("alex");
list.add("front");
BiConsumer<List<String>, String> v = List::add;
System.out.println(v == null);
v.accept(list, "ddd");
System.out.println(list);
}
IDE为IDEA,不报错,正常运行。
我的疑问在于为什么下面这句话没有报错:
BiConsumer<List<String>, String> v = List::add;
List是个接口,add方法只有声明没有具体的实现,而且其前面明显和BiConsumer接口的accept不匹配。
BiConsumer接口定义:
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}
List::add的方法签名:
boolean add(E e);
————————————————————————————————————————————
另外如果我把泛型去掉,变成下面这样就报错了:
BiConsumer v = List::add;
这又是为什么?
https://stackoverflow.com/que...
那只是方法引用,你可以当成是简写。你展开成lambda表达式就明白了。