Java lower bound wildcards

后端 未结 4 1605
孤街浪徒
孤街浪徒 2020-12-14 09:59

I\'m struggling to get my head around this and was wondering if someone could explain the reasons for this.

I have three classes:

class Angel {}
clas         


        
4条回答
  •  一整个雨季
    2020-12-14 10:30

    Your intuitive logic says "a List is a list of things that are a Person or a supertype of Person, so naturally I can add an Angel into it". That interpretation is wrong.

    The declaration List list guarantees that list will be of such a type that allows anything that is a Person to be added to the list. Since Angel is not a Person, this is naturally not allowed by the compiler. Consider calling your method with insertElements(new ArrayList). Would it be okay to add an Angel into such a list? Definitely not.

    The best way to reason about it is that List is no definite type: it is a pattern describing a range of types that are allowed as an argument. Look at List as not a subtype of List, but a type that matches this pattern. The operations allowed on List are those that are allowed on any matching type.

提交回复
热议问题