In java generic I understood what are the meanign of wild card, super and extends, but didn't get why does not allow me to add anything, and why allows me to add upto SomeType in hierarchy, but not above in the hierarchy?
class Animal {}
class Cat extends Animal{}
following method can take list of Animal or sub of Animal i.e Cat, but nothing else
and I am not allowed to add anything, if try to add, compiler stops me why ?
void addAminal(List<? extends Aminal> aList){
aList.add(new Cat()); // compiler error
aList.add(new Animal()); // compiler error
}
Now following method can take any list of Animal or any super type of Animal, but no sub type of Animal, and I can add objects upto Animal or lower in hierarchy, so when I try to add Object, compiler complains why ?
void addAnimal(List<? super Animal> aList){
aList.add(new Animal()); // no error
aList.add(new Cat()); // no error
aList.add(new Object()); // compiler error why ?
}
Thanks
Arya
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…