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 Som
List extends Animal>
means List
where X
is an unknown subtype of Animal
.
Therefore it has methods
void add(X item);
X get(int i);
You can't call add(cat), because we don't know if Cat is a subtype of X. Since X
is unknown, the only value that we knows is a subtype of X
is null
, so you can add(null)
but nothing else.
We can do Animal a = list.get(i)
, because the method returns X
and X
is a subtype of Animal
. So we can call get(i)
and treat the return value as an Animal.
Conversely, List super Animal>
means List
where Y
is an unknown super type of Animal
. Now we can call add(cat)
, because Cat is a subtype of Animal, Animal is a subtype of Y
, therefore Cat is a subtype of Y
, and add(Y)
accepts a Cat. On the other hand, Animal a = list.get(0)
won't work now, because Animal is not a super type of the return type Y
; the only known super type of Y
is Object, so all we can do is Object o = list.get(0)
.