I am attempting to create a Priority Queue of tasks in Java, but I have run into a class casting exception in the constructor of the Priority Queue. Here is my task class:
public class Task <E,T extends Integer>
{
private E job;
private T priority;
public Task(E job, T priority)
{
this.job = job;
this.priority = priority;
}
public String toString()
{
return "Job Name: "+ job + " Priority: "+priority;
}
}
The error gets thrown on the second line of the Priority Queue's constructor:
public class PriorityQueueCustom <E,T extends Integer>
{
private Task<E,T>[] heap;
private int heapSize,capacity;
public PriorityQueueCustom(int capacity)
{
this.capacity = capacity + 1;
heap = (Task<E,T>[]) new Object[capacity];
heapSize = 0;
}
What I don't understand is why I can't cast the Object to a Task since task should extend Object automatically, but I am new to generics so I am not sure if I have set them up correctly?
This is how I created the Priority Queue:
PriorityQueueCustom<String,Integer> queue = new PriorityQueueCustom<String,Integer>(10);
And here is the exception generated:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LPriorityQueueCustom$Task;
at PriorityQueueCustom.<init>(PriorityQueueCustom.java:28)
at PriorityQueueTester.main(PriorityQueueTester.java:5)