Java 泛型 - 超类型引用
如果我正确理解了泛型,那么参数声明为 将接受类型
T
或超类型 T
的任何引用。我试图用下面的代码来测试它,但编译器不喜欢它。
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
class ZiggyTest2{
public static void main(String[] args){
List<Animal> anim2 = new ArrayList<Animal>();
anim2.add(new Animal());
anim2.add(new Dog());
anim2.add(new Cat());
testMethod(anim2);
}
public static void testMethod(ArrayList<? super Dog> anim){
System.out.println("In TestMethod");
anim.add(new Dog());
//anim.add(new Animal());
}
}
编译器错误是:
ZiggyTest2.java:16: testMethod(java.util.ArrayList<? super Dog>) in ZiggyTest2 cannot be applied to (java.util.List<Animal>)
testMethod(anim2);
^
1 error
我不明白为什么我不能传入 anim2,因为它的类型是
并且 Animal 是 Dog 的超类型。
谢谢
If i have understood generics correctly, a method with parameters declared as <? super T>
will accept any reference that is either of Type T
or a super type of T
. I am trying to test this with the following bit of code but the compiler does not like it.
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
class ZiggyTest2{
public static void main(String[] args){
List<Animal> anim2 = new ArrayList<Animal>();
anim2.add(new Animal());
anim2.add(new Dog());
anim2.add(new Cat());
testMethod(anim2);
}
public static void testMethod(ArrayList<? super Dog> anim){
System.out.println("In TestMethod");
anim.add(new Dog());
//anim.add(new Animal());
}
}
Compiler error is :
ZiggyTest2.java:16: testMethod(java.util.ArrayList<? super Dog>) in ZiggyTest2 cannot be applied to (java.util.List<Animal>)
testMethod(anim2);
^
1 error
I dont understand why i cant pass in anim2 since it is of type <Animal>
and Animal is a super type of Dog.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试将
List<>
类型的表达式传递到ArrayList<>
类型的参数中。不去上班。这条线要么
应该是
要么
应该是
You are trying to pass an expression of type
List<>
into a parameter of typeArrayList<>
. Not going to work.Either this line
should be
or
should be
您尝试过
< 吗?扩展狗>
?另外我可以问你为什么使用 ArrayList< 吗? super Dog> 而不仅仅是
ArrayList
?也许这个例子只是您想要做的事情的一个简单形式,但它似乎过于复杂。这是泛型的基本示例。希望有帮助。
Have you tried
<? extends Dog>
?Also can I ask why you are using
ArrayList<? super Dog>
rather than justArrayList<Animal>
? Perhaps this example is just a simple form of what you are trying to do but it seems inexplicably over complicated.This is a basic example of generics. Hope it helps.
可以在此处找到有关 Java 泛型的精彩文档/介绍
A nice document/introduction about Java Generics can be found here