I am implementing my own priority queue and using a class called sportsball that uses it. The priority queue is based on generics and uses a Node (T object, int value) (aka Name of player and their score). I am getting a class cast exception error when I try to run the program.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node;
at PriorityQueue.<init>(PriorityQueue.java:35)
at sportsball.main(sportsball.java:48)
The lines in question are: PriorityQueue.java:35:
Node[] array = (Node[])(new Object[initialSize]);
sportsball.java:48:
PriorityQueue<String> queue = new PriorityQueue<String>(start, step);
Thank you for your help!
Note:
When I tried having line PriorityQueue.java:35:
Node[] array = new Node[initialSize];
the error: generic array creation pops up instead.
You cannot cast an Object
to a Node
, so you shouldn't be able to cast an Object[]
to a Node[]
. Just create the Node[]
directly.
Node[] array = new Node[initialSize];
You cannot cast object to the Node as you did
Node[] array = (Node[])(new Object[initialSize]);
hence the exception ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node
ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueue$Node
which is clear that object cannot be castable to Node Type
So you can go with this option
Node[] array = new Node[initialSize];
You cannot simply cast an Object[] to a Node[]. This will indeed generate a ClassCastException. Just create a Node[] instead ( Node[] array = new Node[initialSize];
). Without more code than this, I cannot say anything else about it.
Note that the message of the ClassCastException is already indicating the problem. [Ljava.lang.Object;
refers to Object[]
and similarly, [LPriorityQueue$Node;
refers to Node[]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.