【问题标题】:Polymorphism and ArrayLists in JavaJava中的多态性和ArrayLists
【发布时间】:2013-11-08 07:50:05
【问题描述】:

我有一个类 Cell 和一个类 Neighbour 扩展 Cell。但是当我尝试将ArrayList<Neighbour> 传递给期望ArrayList<Cell> 的函数时出现错误。我错过了什么?

class Cell {
    PVector pos;

    Cell(PVector pPos) {
        pos = pPos.get();
    }
}

class Neighbour extends Cell {
    int borders = 0;

    Neighbour(PVector pPos) {
        super(pPos);
    }
}

private int inSet(PVector pPos, ArrayList<Cell> set) {
    [...]

    return -1;
}

[...]

ArrayList<Neighbour> neighbours = new ArrayList<Neighbour>();
PVector pPos = new PVector(0, 0);

[...]

inSet(pPos, neighbours);

最后一行抛出错误`The method iniSet(PVector, ArrayList) is not applicable for the arguments (PVector, ArrayList);

感谢您的帮助!

【问题讨论】:

标签: java oop arraylist polymorphism


【解决方案1】:

那是因为

List<A> != List<B> ... even if B extends A.

你需要做的是将函数修改为以下

private int inSet(PVector pPos, ArrayList<? extends Cell> set) {
    [...]
    return -1;
}

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    尝试:

    private int inSet(PVector pPos, List<? extends Cell> set)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 2015-07-22
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多