java generic and wild card

前端 未结 4 1768
时光说笑
时光说笑 2020-12-11 10:56

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

4条回答
  •  囚心锁ツ
    2020-12-11 11:27

    List 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 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).

提交回复
热议问题