Trying to write priority queue in Java but getting "Exception in thread "main" java.lang.ClassCastException"
For my data structure class, I am trying to write a program that simulates a car wash and I want to give fancy cars a higher priority than regular ones using a priority queue. The problem I am having has something to do with Java not being able to type cast "Object" as an "ArrayQueue" (a simple FIFO implementation). What am I doing wrong and how can I fix it?
public class PriorityQueue<E>
{
private ArrayQueue<E>[] queues;
private int highest=0;
private int manyItems=0;
public PriorityQueue(int h)
{
highest=h;
queues = (ArrayQueue<E>[]) new Object[highest+1]; <----problem is here
}
public void add(E item, int priority)
{
queues[priority].add(item);
manyItems++;
}
public boolean isEmpty( )
{
retur开发者_Python百科n (manyItems == 0);
}
public E remove()
{
E answer=null;
int counter=0;
do
{
if(!queues[highest-counter].isEmpty())
{
answer = queues[highest-counter].remove();
counter=highest+1;
}
else
counter++;
}while(highest-counter>=0);
return answer;
}
}
EDIT
Thank you both for the quick answer to this question. I solved the problem by following your advice and one other bit of code:
public PriorityQueue(int h)
{
highest=h;
queues = new ArrayQueue[highest+1];
for(int i = 0; i <= highest; i++)
{
queues[i] = new ArrayQueue();
}
}
An Object is an Object and (in most cases) not an ArrayQueue. So indeed the cast is not possible.
Creation of generic arrays is a problem too, but in your case, this should work:
public PriorityQueue(int h)
{
highest=h;
queues = new ArrayQueue[highest+1]; // Gives an ignorable warning
}
EDIT
The way it is explained in your textbook is incorrect, the book needs a new revision cycle ;) The suggested cast is not allowed in Java, it's like an attempt to do
String forEverUseless = (String) new Object(); // this will not give an empty String
// but an ouch-that-hurts-Exception
which is more obvious. You can never cast a class to one of its subtypes (derived classes). This is true for all classes, including arrays and generic classes.
EDIT 2
Two more suggestions:
- The 'add' method should get a check whether 'priority' is in the valid range of priorities, otherwise add will throw an exception (like in:
queue.add(entry, -1)
) - A remove method usually has an argument - you might want to call it with the element that shall be removed from the queue. (Or - if you're intention is something else, i suggest using the common queue operation names pop, push and peek)
The problem is almost exactly what you said -- you're making something of type Object[]
and trying to cast it to ArrayQueue[]
, and those aren't compatible types. You should just do:
queues = new ArrayQueue[highest+1];
精彩评论