1

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

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 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 Answers3

4

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.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

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)
Eric
  • 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