【发布时间】:2019-08-19 02:45:29
【问题描述】:
- 关于通配符的问题
例子: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
我已阅读问题“capture#1-of ? extends Object is not applicable”下方的答案
您正在使用通用通配符。您不能执行添加操作,因为类类型不确定。您不能添加/放置任何东西(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));
}
}
当返回类型是 Function<V,R> 并且输入类型是 V 时,为什么 before 被设计为 Function<? super V, ? extends T> 而不是 Function<V,T> ? (还是可以通过编译灵活使用)
【问题讨论】:
-
见:What is PECS (Producer Extends Consumer Super)? --- 我相信一旦你理解了 PECS 的含义,你就会得到答案。