Here is what I know:
Double
is a subtype of Number
and List<Double>
is not a subtype of List<Number>
.List<Dog>
is not a subtype of List<Animal>
because you can add Cat
to List<Animal>
but you can't do that with List<Dog>
.List<? extends Number>
means this list can store variables of type Number and variables of subtype of Number. List<Double>
means this list can store variables of type Double.Please correct me if anything above is wrong and then Is List<Double>
a subtype of List<? extends Number>
and why?
Although Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> and, in fact, these two types are not related.
A List is a list that guarantees that every of it's members is an integer. A List makes no such guarantee, it can be some other type. On the other hand List does not make such a guarantee.
That is, ArrayList<String> is a subtype of List<String> , since ArrayList is a subtype of List and both have the same parametric type String .
type 'int' is not a subtype of type 'double'
All your items are correct.
Double
is a subtype ofNumber
andList<Double>
is not a subtype ofList<Number>
.
List<Dog>
is not a subtype ofList<Animal>
because you can addCat
toList<Animal>
but you can't do that withList<Dog>
.
That's correct. Generics aren't covariant (but arrays are!). Here's some follow up reading: Why are arrays covariant but generics are invariant?
List<? extends Number>
means this list can store variables of typeNumber
and variables of subtype ofNumber
.List<Double>
means this list can store variables of typeDouble
.
This is true, but there's an important difference between List<Number>
and List<? extends Number>
. You can think of List<? extends Number>
as a list of a specific Number
-subtype (that is one of List<Double>
, List<Integer>
, List<Long>
, ...) and a List<Number>
as a list that can potentially contain a mix of Double
, Integer
, ...
As for your final question:
Is
List<Double>
a subtype ofList<? extends Number>
...
Yes, you can have for instance
List<Double> doubles = new ArrayList<>();
List<? extends Number> 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<Number>
you won't be able to pass a List<Double>
to it. (Your second item in your question explains why!) Instead, you can let the parameter have type List<? extends Number>
. Since List<Double>
is a subtype of List<? extends Number>
it will work out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With