传递ArrayList< Subclass>到用List< Superclass>声明的方法 [英] Passing ArrayList<Subclass> to method declared with List<Superclass>
问题描述
public static void readList(List< ModelObject> list)$ b我有一个包含泛型参数的方法。 $ b {
//更多代码
}
我想通过 ArrayList
of ModelObjectImplementation
s to this method。
的ArrayList< ModelObjectImplementation>我的列表;
myList = ...
readList(myList); //给出编译错误
ModelObject
是一个接口 ModelObjectImplementation
实现。如何修改方法声明以允许这样做?
如果您使用的是Java版本1.5,则可以使用通配符,更高。
public static void readList(List< ;? extends ModelObject> list)
pre>
这个解决方案更通用,因为它适用于所有
java.util.List
接口实现和子类/ModelObject的子接口
。
详情请参阅通配符教程I have a method with a parameter containing generics.
public static void readList(List<ModelObject> list) { // more code }
I want to pass an
ArrayList
ofModelObjectImplementation
s to this method.ArrayList<ModelObjectImplementation> myList; myList = ... readList(myList); // gives compilation error
ModelObject
is an interface thatModelObjectImplementation
implements. How can I change the method declaration to allow this?解决方案You can use wildcards, if you're using Java version 1.5 and higher.
public static void readList(List<? extends ModelObject> list)
This solution is more generic, because it fits for all
java.util.List
interface implementations and subclasses/subinterfaces ofModelObject
. For more details go to wildcards tutorial这篇关于传递ArrayList< Subclass>到用List< Superclass>声明的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!