泛型:列表<?延伸动物>和 List<Animal> 一样吗? [英] Generics : List<? extends Animal> is same as List<Animal>?
问题描述
我只是想了解 Java 泛型中的 extends
关键字.
I am just trying to understand the extends
keyword in Java Generics.
列表
意味着我们可以在 List
中填充任何对象,其中 IS A Animal
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>
有人可以帮我知道上面两者之间的区别吗?对我来说 extends
在这里听起来有些多余.
Can someone help me know the difference between the above two? To me extends
just sound redundant here.
谢谢!
推荐答案
List
是 List
,但不是 List
的子类型.
List<Dog>
is a subtype of List<? extends Animal>
, but not a subtype of List<Animal>
.
为什么 List
不是 List
的子类型?考虑以下示例:
Why is List<Dog>
not a subtype of List<Animal>
? Consider the following example:
void mySub(List<Animal> myList) {
myList.add(new Cat());
}
如果允许您将 List
传递给此函数,则会出现运行时错误.
If you were allowed to pass a List<Dog>
to this function, you would get a run-time error.
现在,如果我们使用 List 相反,将发生以下情况:
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
}
你可以向这个函数传递一个List
,但是编译器意识到向列表中添加一些东西会给你带来麻烦.如果你使用 super
而不是 extends
(允许你传递一个 List
),情况正好相反.
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
}
这背后的理论是协方差.
这篇关于泛型:列表<?延伸动物>和 List<Animal> 一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!