Solace Solace - 5 months ago 16
Java Question

Is List<?> the common parent of List<Integer> and List<Number>?

From this Oracle tutorial,


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.

The common parent of
List<Number>
and
List<Integer>
is
List<?>
.


My question is about the second sentence. How can we say that
List<?>
is the common parent of
List<Number>
and
List<Integer>
?


?
stands for an unknown type, which could be any reference type. Even if I say that
?
would be
Object
here,
Object
being the common parent of
Integer
and
Number
does NOT mean that
List<Object>
becomes a common parent of
List<Integer>
and
List<Number>
.

Answer

The context you need to understand is not of Integer or Number but it's the List. Let's suppose you were the one creating the List class then how would you create the class so it will only support a specific type of class.

Yes, that List class won't use Object as its type but instead use a wild card ?.

As documentation of WildCards say

So what is the supertype of all kinds of collections? It's written Collection<?> (pronounced "collection of unknown")

Same thing can be said for List.

So what is the supertype of all kinds of Lists? It's written List<?> (pronounced "List of unknown")

Comments