Java中的多态性和ArrayLists

时间:2013-11-08 07:50:06

标签: java oop arraylist polymorphism

我有一个课程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);

最后一行抛出错误`方法iniSet(PVector,ArrayList)不适用于参数(PVector,ArrayList);

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

那是因为

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

您需要做的是将功能修改为以下

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

希望有所帮助。

答案 1 :(得分:2)

尝试:

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