我有一个HeapInterface和一个带有基于数组的实现的Heap类。我试图制作整数类的堆,但我收到以下错误:
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)
我将提供每个类的声明,构造函数和产生错误的测试方法,希望有人可以解释我的错误......
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);
}
}
有什么想法吗?
答案 0 :(得分:0)
你不能将一个Object []强制转换为T [],同时断言T是可比较的,因为一个对象不具有可比性。尝试创建Comparable[]
并将其投射到T[]
:
T[] tempHeap = (T[]) new Comparable[capacity];