[英]Issue with <T extends Comparable<? super T>>
我有一個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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.