java generic and wild card

前端 未结 4 1792
时光说笑
时光说笑 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条回答
  •  Happy的楠姐
    2020-12-11 11:12

    The generics only allow you to add an object of the type (or a subtype) of the type given as type parameter. If you put it means the list has SOME type that is a subclass of animal. Since you are trying to add a Cat to it, you have to be sure that it is indeed a list of Cats, and not of Dogs.
    Basically, when you use a wildcard you will not be able to add new items to such a list (note: I don't have full knowledge and this might not be fully correct, but it seems like this. Forgive me if I'm wrong)

    If you want to be able to add any Animal to the list, just use List.

提交回复
热议问题