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
Java Generics: set List of superclass using List of subclass
提问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
回答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
回答by Manuel Darveau
Do:
做:
setSuperClassList(List<? extends Superclass> list)
This will allow a list of any subclass of Superclass.
这将允许列出超类的任何子类。

