【发布时间】:2015-06-25 04:16:55
【问题描述】:
我可以使用基本的泛型表达式,但通配符约束让我很困惑。
信息:学生扩展人,人扩展动物
List<? super Animal> aList= new ArrayList<>();
// does not compile as expected,
// since the list is restricted to something that has Animal as superclass.
// aList.add(new Object());
aList.add(new Animal()); // I can add animal
aList.add(new Person()); // I can add Person
aList.add(new Student()); // I can add Student
Animal a = new Animal();
Animal b = new Animal();
Person p = new Person();
Student s = new Student();
// test
a = b; //I can assign an animal to another animal
a = p; // I can assign a person to an animal
a = s; // I can assign a student to an animal
Animal animal = aList.get(0); // DOES NOT COMPILE, WHY ?
问题:我不明白为什么最后一个作业不起作用。上面的例子表明,该列表中的任何东西都肯定是动物,但我无法从该列表中获取动物。
更具体:当我知道我只能添加以 Animal 作为超类的类型时,为什么我不能期望从 Animal 类型中删除对象?
事实:我只能添加扩展 Animal 的对象!我只是尝试添加一个汽车对象,但它不起作用!
我开始怀疑我的理智了,希望你能帮助我。谢谢你
另外:
Object animal = aList.get(0); // works
为什么即使我知道我不能添加 Object-Type,这个语句仍然有效?
解决方案:(基于接受的答案)
我误解了<? super Animal>的意思
我认为这是什么意思:任何将 Animal 作为超类的类。
它(显然)是什么意思:任何作为动物超类的类。
因此,List 也可能包含 Object 类型的对象,这就是 Animal animal = aList.get(0); 失败的原因。
干杯
【问题讨论】:
-
我想你只是想要: List
在你的 aList 声明中 -
Animal animal = aList.get(1)怎么样(以你的例子)?如果你能回答这个问题,那么你就有理由不被允许。 -
您确定您正确区分了
super和extends? stackoverflow.com/questions/4343202/… -
List<? super Animal>not 的意思是:“以 Animal 作为超类的东西”,它的意思是:某个未知类型,它是Animal的超类。因此,与您在评论中所说的相反。 -
@Seelenvirtuose:人是人,人是哺乳动物,哺乳动物是动物。或:(人->人类)&&(人类->哺乳动物)&&(哺乳动物->动物)人->动物。 (当然除了那些用裂口雕刻的粘土制成的。)