Java 接受扩展对象的对象列表
我们有一个方法,它接受一个Java 接受扩展对象的对象列表,java,arraylist,Java,Arraylist,我们有一个方法,它接受一个矩形形状类型的列表 void foo(List<RectangularShape> recs) { // ... } void foo(List<? extends RectangularShape> recs) { // this method accept List of RectangularShape or it's sub types } 然后我们尝试调用foo方法: fo
矩形形状
类型的列表
void foo(List<RectangularShape> recs) {
// ...
}
void foo(List<? extends RectangularShape> recs) { // this method accept List
of RectangularShape or it's sub types
}
然后我们尝试调用foo方法:
foo(rectangles);
首先,它不适用于
列表
,但这不是我的主要问题。如果我将其更改为ArrayList
,那么它不适用于ArrayList
,但为什么不适用呢?因为Rectangle2D
在我的逻辑中扩展了rectangleshape
,所以它应该是可能的。您需要这样声明您的方法:
void foo(List<? extends RectangularShape> l) {
...
}
<E extends RectangularShape> void foo(List<E> recs) {
...
}
void foo(Listvoid foo(List您要查找的是通用边界,如下所示:
有关如何使用通用边界的详细信息:
基本上,您需要使用通配符运算符作为
void foo(List<? extends RectangularShape> recs) {
...
}
void-foo(列表更改为List-rectangles=new-ArrayList();
如果使用void-foo(List-recs){…},您计划执行的操作是可能的
这并不能解决问题,类型列表
仍然与列表
不兼容。即使您可以引用E
,但您对E
所做的事情与矩形形状
所做的事情是完全不同的。事实上,这是因为您无法访问E.class
,但您可以访问Recta>ngularShape.class
@JamieCockburn我明白了!这是一个公平的观点。考虑到编译器本身可以根据给定列表的类型计算出E
的类型,这两者在功能上有什么区别吗?我现在想不出任何区别。@Zhuinden如果我使用第一种方法,我如何获得迭代器?@Zhuinden不,两者之间没有区别。编译器实际上会丢弃这些信息,因此在运行时,没有人知道s之间有什么。这称为类型擦除。@clankill3r只需使用for(RectangularShape:recs)
来迭代列表。
List<Rectangle2D> rectangles = new ArrayList<Rectangle2D>();
void foo(List<? extends RectangularShape> recs) {
...
}
<E extends RectangularShape> void foo(List<E> recs) {
...
}