62,635
社区成员




如题,在网上看到的通配符多用在集合中,表示集合中元素为该类或其子类类型。如果返回值或参数直接是想用通配符描述,该怎么写。
我这个例子中方法add向容器中添加Employee,运行时报错。说“java: 不兼容的类型: ch08.Employee无法转换为capture#1, 共 ? extends ch08.Employee”。
package ch08;
import java.util.List;
public class Test {
public static void main(String[] args) {
//
Test t1 = new Test();
t1.add(new Manager("", 0));
}
public void add(Employee value) {
// 此处报错。
// Required type: capture of ? extends Employee
// Provided: Employee
list.add(value);
}
private List<? extends Employee> list;
}
private List<? extends Employee> list 替换 private List list 或 List<? super Employee> list