Is List a subtype of List<? extends Number> and why?

后端 未结 4 1359
逝去的感伤
逝去的感伤 2021-02-05 18:37

Here is what I know:

  1. Double is a subtype of Number and List is not a subtype of List
4条回答
  •  佛祖请我去吃肉
    2021-02-05 19:03

    All your items are correct.

    1. Double is a subtype of Number and List is not a subtype of List.

    2. List is not a subtype of List because you can add Cat to List but you can't do that with List.

    That's correct. Generics aren't covariant (but arrays are!). Here's some follow up reading: Why are arrays covariant but generics are invariant?

    1. List means this list can store variables of type Number and variables of subtype of Number. List means this list can store variables of type Double.

    This is true, but there's an important difference between List and List. You can think of List as a list of a specific Number-subtype (that is one of List, List, List, ...) and a List as a list that can potentially contain a mix of Double, Integer, ...

    As for your final question:

    Is List a subtype of List...

    Yes, you can have for instance

    List doubles = new ArrayList<>();
    List numbers = doubles;
    

    ... and why?

    This is just the way subtyping is defined.

    As for the motivation, suppose you have a method that accepts a list of numbers. If you let the parameter have the type List you won't be able to pass a List to it. (Your second item in your question explains why!) Instead, you can let the parameter have type List. Since List is a subtype of List it will work out.

提交回复
热议问题