java generic and wild card

前端 未结 4 1794
时光说笑
时光说笑 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:13

    Well, When you say ArrayList< ? extends Animal > you are specifying that this list will contain any specific type (as ? refers to a specific/definite type) that is of type Animal or anything inherited from Animal but something definite. So ultimately, as the generics are implemented with Eraser concept (which replaces every generic type in the program by a non-generic upper bound), this list is supposed to contain a specific type but due to ( < ? extends Animal >) you don't know which specific type is that. And hence you are not allowed to add even though types are inherited from Animal.

    But when you say ArrayList< ? super Animal >, it means the arraylist contains specific type derived from Animal that is, objects whose base or super type is Animal. Hence it is safe to pass a Animal or anything derived from Animal into this list. The list is treated that way and it is allowed to add objects as mentioned. And hence it works.

    Hope it helps!

提交回复
热议问题