Java Generics: set superclass list using subclass list

If I have a method in MyClass , for example

 setSuperClassList(List<Superclass>) 

... should I do this:

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

This does not seem to compile. Why?

+6
java generics class hierarchy
source share
4 answers

Try setSuperClassList(List<? extends Superclass>) .

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

+19
source share

You just make generics a little wrong. Add a bit ? extends ? extends , which allows the passed list to contain SuperClass or any of its subclasses.

 setSuperClassList(List<? extends Superclass>) 

This is called setting an upper bound for generics.

The List<Superclass> statement says that the List can only contain SuperClass . This excludes any subclasses.

+5
source share

It will not compile since java.util.List not covariant .

Try setSuperClassList(List<? extends Superclass>) .

+1
source share

do:

 setSuperClassList(List<? extends Superclass> list) 

This will allow a list of any subclass of the Superclass.

0
source share

All Articles