Reputation: 448
I would like to cast an array of object which involves a generic type for strictly internal usage.
The object:
private class Node<T>
{
T element;
int prior;
public Node(T element, int prior)
{
this.element=element;
this.prior=prior;
}
}
The array:
private Node<E>[] elements;
The cast:
public PriorityQueue()
{
elements = (Node<E>[])new Object[capacity]; // ClassCastException
}
Why do i get ClassCastException?
Upvotes: 3
Views: 2809
Reputation: 726479
The reason the cast does not work is that type erasure of Node<E>
applies to E
inside Node
, but it does not apply to arrays of Node<E>
.
Type erasure would let you cast Node<E>
to Node<Object>
because all Node<E>
s are Node<Object>
under the hood. Similarly, it would let you cast Node<E>[]
to Node<Object>[]
and back, because the arrays share the same underlying type - that is, Node<Object>
.
However, type erasure is not in play when you deal with arrays. An array of objects remains an array of objects, and Java has enough metadata to know it.
You have several ways of solving this problem:
Node<E>[]
to ArrayList<Node<E>>
- array list has similar footprint and access times, and is genericClass<E>
.Upvotes: 0
Reputation: 2655
The accepted solution from here ought to do the trick:
casting Object array to Integer array error
You can't cast an Object[] to a Node[] directly, but you can use Arrays.copyOf() to create a copy of the right type. Only downside is this involves doing a copy, but it's Java: if you wanted it to not be slow you wouldn't have done this to yourself ;)
Upvotes: 1