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( )
{
return (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();
}
}