Re: Overriding Generics
Bryan wrote:
Another generics overriding question -- say I have the method below:
public List<? extends Foo> getFooList() { ... }
When I try and do this:
List<Foo> l = getFooList();
I get the following error:
Type mismatch: cannot convert from List<capture-of ? extends Foo> to
List<Foo>
Can anyone explain this to me? Thanks!
It's pretty much the same as the other question. You can only upcast the
result of any method to a supertype of the return type. List<Foo> is not a
supertype of List<? extends Foo>. So you get the error that you cannot
convert the type.
Start here:
<http://java.sun.com/docs/books/tutorial/extra/generics/index.html>
in particular, the topics
<http://java.sun.com/docs/books/tutorial/extra/generics/subtype.html>
and
<http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html>
address this matter.
Let's say the actual runtime return type of the list were 'List<FooSomeSub>'.
Your list 'l' would allow
l.add( new FooSomeOtherSub() );
which would violate the type safety.
The wildcard form prevents such add()s (from the referenced tutorial):
Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.
On the other hand, ... we can call get() and make use of the result.
Another tutorial:
<http://java.sun.com/docs/books/tutorial/java/generics/index.html>
particularly
<http://java.sun.com/docs/books/tutorial/java/generics/subtyping.html>
and
<http://java.sun.com/docs/books/tutorial/java/generics/wildcards.html>
And for the final word, the JLS:
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.5>
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.10>
Subtyping does not extend through generic types: T <: U does not imply that C<T> <: C<U>.
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.10.2>
The relevance of the subtype relationship:
<http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.5>
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4>
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.5>
<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12>
--
Lew