Edit: Noticed the post was flagged as duplicate; I read through the other, similar, question but it really didn't treat the same problem as mine. I'm working with a class that is guaranteed to be of the type Comparable, yet I can't cast it.
I have the following class, which is an implementation of an interface Queue. I make sure that the type which HeapPriorityQueue object works with implements Comparable, so that the method E.compareTo(E other) is available.
I create an instance of HeapPriorityQueue in my main method. Where Patient is a class that implements Comparable
HeapPriorityQueue<Patient> queue = new HeapPriorityQueue<>();
At compilation however, I get an exception ClassCastException which points towards the last line in the code below
public class HeapPriorityQueue<E extends Comparable<E>> implements Queue<E>
{
private final int DEFAULT_CAPACITY = 10;
private int size;
private E[] array;
public HeapPriorityQueue()
{
size = 0;
array = (E[]) new Object[DEFAULT_CAPACITY + 1];
}
}
The exception:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
List<E>) that might better suit you...Listhere, even if you have to write it yourself. As you have found, you cannot donew E[size];and you cannot cast from anObject[]to anE[](which you would not want to do, even if you could, since your newObject[]is full ofObjects and notEs!). Your best bet is probablyArrayList. Whether or not that's allowed is a different question. Although I do have to ask... if it's a HeapPriorityQueue, shouldn't you be setting up a Heap and not an Array/List?Node<E>class that had a value and right and left children. I think the data structure manipulations would be easier that way. But this is veering off-topic for this question...