subtype hierarchy
So lets say I were to draw the class hierarchy of List<?>
. Would List<Object>
be a subtype of List<?>
Then would List<Integer>
be a subtype of List<Object>
or would it be a subtype of List<?>
?
Thanks
Then would
List<Integer>
be a subtype ofList<Object>
?
No, generic classes in Java are not covariant.
From the above link:
It turns out there's a good reason it doesn't work that way: It would break the type safety generics were supposed to provide. Imagine you could assign a
List<Integer>
to aList<Number>
. Then the following code would allow you to put something that wasn't anInteger
into aList<Integer>
:List<Integer> li = new ArrayList<Integer>(); List<Number> ln = li; // illegal ln.add(new Float(3.1415));
List<?>
is slightly different and if I understand it correctly, it is similar to the raw type in the sense that the type parameter here is unknown. Here for instance, the second line compiles fine, but now the third line is illegal, since the compiler can say for sure that it is a legal add
operation:
List<Integer> li = new ArrayList<Integer>();
List<?> ln = li;
ln.add(new Float(3.1415)); // illegal
Thus by assuming the "is assignable to" definition of subtype, I suppose List<Object>
is a subtype of List<?>
.
The only place where a class or interface is it's own child is in the evaluation of generic bounds.
Some example method signatures:
public <E extends<Enum<E>> void doSomeThingWithAnEnum(E item);
public <S extends Comparable<? super S>> void sort(S[] items);
But this is not a real type hierarchy, all of this info is removed by the compiler. The resulting byte code is roughly equivalent to:
public void doSomeThingWithAnEnum(Enum item);
public void sort(Comparable[] items);
精彩评论