开发者

Java Generics: set List of superclass using List of subclass

开发者 https://www.devze.com 2022-12-24 18:26 出处:网络
If I have a method in MyClass such as setSuperClassList(List<Superclass>) ...should I be able to do this:

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>开发者_JAVA技巧())

It appears this won't compile. Why?


Try setSuperClassList(List<? extends Superclass>).

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


You are just doing the generics a bit wrong. Add the ? extends bit, and that will allow the passed in list to contain the SuperClass or any of its subclasses.

setSuperClassList(List<? extends Superclass>)

This is called setting an upper bound on the generics.

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


It won't compile sincejava.util.List is not covariant.

Try setSuperClassList(List<? extends Superclass>) instead.


Do:

setSuperClassList(List<? extends Superclass> list)

This will allow a list of any subclass of Superclass.

0

精彩评论

暂无评论...
验证码 换一张
取 消