[英]Java Generics: set List of superclass using List of subclass
If I have a method in MyClass
such 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?
为什么?
You are just doing the generics a bit wrong. 您只是在做泛型有点错误。 Add the
? extends
添加
? extends
? extends
bit, 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
. 语句
List<Superclass>
表示列表只能包含SuperClass
。 This excludes any subclasses. 这不包括任何子类。
Do: 做:
setSuperClassList(List<? extends Superclass> list)
This will allow a list of any subclass of Superclass. 这将允许列出超类的任何子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.