Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

Polymorphism and ArrayLists in Java

I have a class Cell and a class Neighbour extending Cell. But I get an error when I try to pass an ArrayList<Neighbour> to a function expecting an ArrayList<Cell>. What have I missed?

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 last line throws the error `The method iniSet(PVector, ArrayList) is not applicable for the arguments (PVector, ArrayList);

Thanks for your help!

Upvotes: 0

Views: 181

Answers (2)

Harsha R
Harsha R

Reputation: 817

that is because

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

What you need to do is modify the function to the following

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

Hope that helps.

Upvotes: 3

Jean Logeart
Jean Logeart

Reputation: 53809

Try with:

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

Upvotes: 2

Related Questions