【发布时间】:2020-07-03 10:27:15
【问题描述】:
我正在尝试返回子类对象的数组列表
假设
abstract class Foo {
protected abstract ArrayList<Foo> getAlotOfMyself();
};
是一个超类,它的子类需要返回一个自己的数组, 例如它的子类:
class Bar extends Foo{
public ArrayList<Bar> getAlotOfMyself(){
// Do the interesting stuff
}
};
但是由于java,这不起作用,ArrayList<Foo> 与ArrayList<Bar> 的类型不同,即使Bar 是Foo 的子类
我尝试将 Foo 中的 ArrayList 更改为 ArrayList<? extends Foo>,但它似乎只在 Foo 不是抽象类时才有效(因此 getAlotOfMyself() 在 Foo 中实现),它不会编译说:
cannot convert from ArrayList<capture#1-of ? extends Foo> to ArrayList<Foo>.
导致该错误的原因是这样的
void interestingFunction(Foo foo){
ArrayList<Foo> alot = foo.getAlotOfMyself(); // the compile error happens here
}
当然这个函数只在Bar和其他子类上调用
【问题讨论】:
-
你的“interestingFunction”属于哪个类?
-
它在第三类中,就像一个包装器。
-
好吧,我不确定我是否做了你想要的。也许你可以看看它并获得一些想法。或者也许 Arvind 做了你想做的。
-
ArrayList<? extends Foo>绝对确实有效。但是,如果您的函数返回它,那么您必须将返回的值分配给具有相同泛型类型的变量:List<? extends Foo> alot = foo.getAlotOfMyself();