Reputation: 71
I currently have a Tile
class that extends a Node
class, and want to downcast an array of Nodes to an array of Tiles like so:
class Node<T> {
Node[] neighbours;
private final T value;
}
class Tile extends Node {
public Tile(Point value) {
super(value);
}
Tile[] neighbours = (Tile[]) this.getNeighbours;
}
At the moment the compiler is throwing A ClassCastException and I do not know how to fix it.
I am not 100% familiar with inheritance, but I thought since Tile is a subclass this should be a safe casting from Nodes to Tiles.
Upvotes: 1
Views: 1331
Reputation: 61
You could use a collection, for example something like:
class Node<T> {
List<Node> neighbours;
private T value;
}
class Tile extends Node {
public Tile(String value) {
super(value);
}
List<Tile> neighbours = this.neighbours.stream().filter(item -> item instanceof Tile).map(item -> (Tile) item).collect(Collectors.toList());
}
Upvotes: 0
Reputation: 393836
If Tile
is a sub-class of Node
, all Tile
s a Node
s, but not all Node
s a Tile
s.
Therefore casting a Node[]
to Tile[]
is wrong, since not all Node
arrays are Tile
arrays.
For example, the following will throw ClassCastException
:
Node[] nodes = new Node[10];
Tile[] tiles = (Tile[]) nodes;
On the other hand, the following will work:
Node[] nodes = new Tile[10];
Tile[] tiles = (Tile[]) nodes;
Upvotes: 3