Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 接受扩展对象的对象列表_Java_Arraylist - Fatal编程技术网

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(List
void 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) {
  ...
}