【问题标题】:How can an abstract class return an ArrayList of the subclass object?抽象类如何返回子类对象的 ArrayList?
【发布时间】: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&lt;Foo&gt;ArrayList&lt;Bar&gt; 的类型不同,即使BarFoo 的子类

我尝试将 Foo 中的 ArrayList 更改为 ArrayList&lt;? extends Foo&gt;,但它似乎只在 Foo 不是抽象类时才有效(因此 getAlotOfMyself()Foo 中实现),它不会编译说: cannot convert from ArrayList&lt;capture#1-of ? extends Foo&gt; to ArrayList&lt;Foo&gt;.

导致该错误的原因是这样的

void interestingFunction(Foo foo){
    ArrayList<Foo> alot = foo.getAlotOfMyself(); // the compile error happens here
}

当然这个函数只在Bar和其他子类上调用

【问题讨论】:

  • 你的“interestingFunction”属于哪个类?
  • 它在第三类中,就像一个包装器。
  • 好吧,我不确定我是否做了你想要的。也许你可以看看它并获得一些想法。或者也许 Arvind 做了你想做的。
  • ArrayList&lt;? extends Foo&gt; 绝对确实有效。但是,如果您的函数返回它,那么您必须将返回的值分配给具有相同泛型类型的变量:List&lt;? extends Foo&gt; alot = foo.getAlotOfMyself();

标签: java generics arraylist


【解决方案1】:

试试这个,看看它是否符合你的要求。

import java.util.ArrayList;
import java.util.List;

public class SubclassStuff {

    public static void main(String[] args) {
        Bar b = new Bar();
        b.interestingFunction(b);
    }

}

abstract class Foo {
    public String name;
    public Foo() {
    }
    public Foo (String name) {
        this.name = name;
    }
    protected abstract ArrayList<? extends Foo> getAlotOfMyself();
    public void interestingFunction(Foo foo) {
        System.out.println(foo.getAlotOfMyself());
    }
}

class Bar extends Foo {
    public ArrayList<Bar> getAlotOfMyself() {       
        return new ArrayList<>(List.of(new Bar("I am Bar")));
    }
    public Bar() {
        super();
    }
    public Bar (String name) {
        this.name = name;
    }
    public String toString() {
        return name;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多