What's the difference between List<? extends MyClass>
and List<MyClass>
. Don't both mean that I have a list with objects of MyClass
?

- 176,041
- 30
- 275
- 357

- 25
- 3
-
You will see one difference if you will try to add `MyClass` object to `List extends MyClass>` and to `List
` :) – Pshemo Sep 19 '13 at 00:04
3 Answers
There is a difference. A List<? extends MyClass>
could refer to a List<MySubClass>
, which is different than a List<MyClass>
. Also, a List<MySubClass>
is not a List<MyClass>
, because Java generics are not covariant.
Because the compiler doesn't know which subclass the wildcard actually is, it prevents you from calling add
, to preserve type safety.

- 54,340
- 18
- 130
- 181

- 176,041
- 30
- 275
- 357
List<? extends MyClass>
, when accepted in a method, gives you a list that cannot have things added for type safety, but can actually be read quite nicely. Since we don't know which subclass of MyClass
the list is actually, we cam't add MyClass
. Note that X extends Y
does not imply Foo<X> extends Foo<Y>
, due to lack of covariance.
For List<MyClass>
you can read and write nicely to it.

- 40,330
- 4
- 86
- 117
-
@Thilo I'd have to do experimentation for the null case when I have time. – nanofarad Sep 19 '13 at 00:10
-
1"Oh, this one again?" Maybe you could help look for/vote to close as a duplicate. – Paul Bellora Sep 19 '13 at 00:16
GenericClass<? extends T> g
allows you to use a generic return type for a method in GenericClass
:
T item = g.get(0)
GenericClass<? super T> g
allows you to use a generic argument type for a method in GenericClass
:
T item;
g.set(0, item)

- 95,302
- 53
- 242
- 374
-
GenericClass? `get` and `set` are defined in `List`. How they would work for "GenericClass" is completely up for grabs. – Thilo Sep 19 '13 at 00:18