Java Generic(List <t> list1)VS(List <! - ?super SuperClass - > list2)

时间:2015-12-09 11:01:54

标签: generics

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);

1 个答案:

答案 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()