本文介绍了泛型:列表<?延伸动物&gt;与List&lt; Animal&gt;相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



名单< ;? extends Animal> 表示我们可以在扩展Animal> ,但不是 List< Animal> 。

的子类型。

是列表< Dog> 不是列表< Animal> 的子类型?考虑下面的例子:

  void mySub(List< Animal> myList){
myList.add(new Cat ));





如果您被允许传递列表< Dog> ; 到这个函数,你会得到一个运行时错误。






编辑:Now ,如果我们使用 List ,则会发生以下情况:

  void mySub(List< ;? extends Animal> myList){
myList.add(new Cat()); //在这里编译错误
Animal a = myList.get(0); //正常工作

$ / code $ / pre
$ b $您可以传递一个列出< Dog> 这个函数,但是编译器意识到添加一些东西到列表可能会让你陷入困境。如果您使用 super 而不是 extends (允许您传递 List< LifeForm> ),这是相反的方式。

  void mySub(List< ;? super Animal> myList){ 
myList.add(new Cat()); //正常工作
Animal a = myList.get(0); //在此处编译错误,因为列表条目可能是Plant
}

理论在这之后是。


I am just trying to understand the extends keyword in Java Generics.

List<? extends Animal> means we can stuff any object in the List which IS A Animal

then won't the following also mean the same thing:

List<Animal>

Can someone help me know the difference between the above two? To me extends just sound redundant here.

Thanks!

解决方案

List<Dog> is a subtype of List<? extends Animal>, but not a subtype of List<Animal>.

Why is List<Dog> not a subtype of List<Animal>? Consider the following example:

void mySub(List<Animal> myList) {
    myList.add(new Cat());
}

If you were allowed to pass a List<Dog> to this function, you would get a run-time error.


EDIT: Now, if we use List<? extends Animal> instead, the following will happen:

void mySub(List<? extends Animal> myList) {
    myList.add(new Cat());     // compile error here
    Animal a = myList.get(0);  // works fine
}

You could pass a List<Dog> to this function, but the compiler realizes that adding something to the list could get you into trouble. If you use super instead of extends (allowing you to pass a List<LifeForm>), it's the other way around.

void mySub(List<? super Animal> myList) {
    myList.add(new Cat());     // works fine
    Animal a = myList.get(0);  // compile error here, since the list entry could be a Plant
}

The theory behind this is Co- and Contravariance.

这篇关于泛型:列表<?延伸动物&gt;与List&lt; Animal&gt;相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:13