我有一个HeapInterface和一个基于数组的实现的Heap类。我正在尝试制作Integers类的堆,但是出现以下错误:
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);
}
}
有任何想法吗?
在断言T是可比较的时,您不能将Object []强制转换为T [],因为Object是不可比较的。尝试创建一个Comparable[]
并将其转换为T[]
:
T[] tempHeap = (T[]) new Comparable[capacity];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句