Dheeraj Kumar Singh Dheeraj Kumar Singh - 1 month ago 10
Java Question

Difference between List<? extends MyClass> and List<MyClass>

What's the difference between

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

Answer

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.

Comments