Java Generics: set List of superclass using List of subclass

Drew Johnson picture Drew Johnson · Mar 24, 2010 · Viewed 10.7k times · Source

If I have a method in MyClass such as

setSuperClassList(List<Superclass>)

...should I be able to do this:

new MyClass().setSuperClassList(new ArrayList<Subclass>())

It appears this won't compile. Why?

Answer

Thomas L&#246;tzer picture Thomas Lötzer · Mar 24, 2010

Try setSuperClassList(List<? extends Superclass>).

Also check PECS to see wether you should use ? extends or ? super.