java Java泛型:使用子类列表设置超类列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2511103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:34:04  来源:igfitidea点击:

Java Generics: set List of superclass using List of subclass

javagenericsclasshierarchy

提问by Drew Johnson

If I have a method in MyClasssuch as

如果我有一个方法,MyClass例如

setSuperClassList(List<Superclass>)

...should I be able to do this:

...我应该能够做到这一点:

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

It appears this won't compile. Why?

看来这不会编译。为什么?

回答by Thomas L?tzer

Try setSuperClassList(List<? extends Superclass>).

试试setSuperClassList(List<? extends Superclass>)

Also check PECSto see wether you should use ? extendsor ? super.

还要检查PECS以了解您是否应该使用? extends? super

回答by jjnguy

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

你只是在做泛型有点错误。添加该? extends位,这将允许传入的列表包含 SuperClass 或其任何子类。

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.

声明List<Superclass>说列表只能包含SuperClass. 这不包括任何子类。

回答by missingfaktor

It won't compile sincejava.util.Listis not covariant.

它不会编译,因为java.util.List不是covariant

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

试试吧setSuperClassList(List<? extends Superclass>)

回答by Manuel Darveau

Do:

做:

setSuperClassList(List<? extends Superclass> list)

This will allow a list of any subclass of Superclass.

这将允许列出超类的任何子类。