I have a HeapInterface, and a Heap class with an array-based implementation. I'm trying to make a Heap of the class Integers, but I'm getting the following error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
at HeapArray.<init>(HeapArray.java:16)
at HeapArray.<init>(HeapArray.java:10)
at Test.main(Test.java:5)
I'll provide the declaration of each class, the constructors, and the test method that produced the error in hopes someone can explain my error...
public interface HeapInterface<T extends Comparable<? super T>> {...}
public class HeapArray<T extends Comparable<? super T>> implements HeapInterface<T> {
private T[] heap;
private static final int DEFAULT_CAPACITY = 10;
private int numberOfEntries;
public HeapArray() {
this(DEFAULT_CAPACITY);
}//end default constructor
public HeapArray(int capacity) {
numberOfEntries = 0;
@SuppressWarnings("unchecked")
T[] tempHeap = (T[]) new Object[capacity];
heap = tempHeap;
}//end alternative constructor
...
}
public class Test {
public static void main(String[] args) {
HeapInterface<Integer> h = new HeapArray<Integer>();
for(int i = 0; i < 16; i++)
h.add(i);
System.out.println(h);
}
}
Any ideas?
You can't cast an Object[] to a T[] whilst asserting that T is comparable as an Object is not comparable. Try creating a Comparable[]
and casting it to a T[]
:
T[] tempHeap = (T[]) new Comparable[capacity];
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.