关于通配符的问题
例子:Student extends Person
Person person = new Person();
Student student = new Student();
List<? super Student> list = new ArrayList<>();
list.add(student); // success
list.add(person); // compile error
List<? extends Person> list2 = new ArrayList<>();
list2.add(person); // compile error
list2.add(student);// compile error
您正在使用通用通配符。您无法执行添加操作,因为类类型不确定。你不能添加/放置任何东西(null 除外)——Aniket Thakur
官方文档:通配符从不用作泛型方法调用、泛型类实例创建或超类型的类型参数
但是为什么能list.add(student)
编译成功呢?
的设计java.util.function.Function
public interface Function<T, R>{
//...
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
}
为什么before设计为Function<? super V, ? extends T>而不是Function<V,T>当返回类型是Function<V,R>并且输入类型是V?(还可以通过编译灵活使用)
HUX布斯
沧海一幻觉
相关分类