使用ArrayList <subclass>作为方法参数,其中参数类型为ArrayList <superclass> </superclass> </subclass>

时间:2012-07-22 23:00:14

标签: function inheritance parameters casting arraylist

所以我有两节课。类B扩展了类A。我正在创建包含ArrayList类型对象的B,因此列表的类型为ArrayList<B>。我想在输入参数类型为ArrayList的方法useList中使用ArrayList<A>。由于BA的子类,因此可以在A的任何位置使用它,包括在此应用程序中。

但是,编译器似乎不喜欢这样(请参阅下面的代码中的错误消息)。当我将ArrayList<B>传递给方法时,我也尝试将ArrayList<A>投射到public class Test { private class A { } private class B extends A { } public static void useList(ArrayList<A> aList) { } public static void main(String[] args) { ArrayList<B> bList = new ArrayList<B>(); /* "The method test(ArrayList<Test.A>) in the type Test * is not applicable for the arguments (ArrayList<Test.B>)" */ useList(bList); /* "Cannot cast from ArrayList<Test.B> to ArrayList<Test.A>" */ useList((ArrayList<A>)bList); } } ,但是那个也没有用。

代码:

{{1}}

我无疑在做些傻事,所以任何建议都会受到赞赏!

谢谢!

1 个答案:

答案 0 :(得分:3)

只需声明useList以期望ArrayList类型的参数包含扩展A的元素:

public static void useList(ArrayList<? extends A> aList) { }