Q值。为什么第一个没有工作,但第二个工作正常。?
1
public List<? extends Animal> doAdd(List<? extends Animal> list) {
//here unable to add, compilation error
list.add(new Cat());
return list;
}
2
private static <T> List<T> doAdd(List<T> list){
//working fine.
ls.add((T) new Cat());
return ls;
}
List<Animal> list = new ArrayList<Aninal>();
doAdd(list);
答案 0 :(得分:0)
? extends Sometype
不允许您添加null
以外的任何内容。? extends Sometype
允许我们引用子类型。
让我们举个例子
List<? extends Animal> list = new ArrayList<Dog>(); // this assignment works because of ? extends Animal and Dog is a subtype of Animal
list.add(new Cat()); // this will give a compiler error
但假设如果add()工作,你可以将Cat
添加到Dog
列表中,这会破坏泛型提供的编译时间检查的想法。这就是为什么{ {1}}阻止您添加? extends Sometype
在第二种情况下,你需要一个演员,因为该方法本身并不知道null
会是什么,所以T
会在没有演员的情况下失败。
您可以更新第二个方法定义,以允许ls.add((T) new Cat());
在没有强制转换的情况下工作。
add()