![](/img/trans.png)
[英]Implementing a sort of key-value pair (not essentially a HashMap) in Java
[英]Implementing MaxHeap with Key,Value Pair
我正在Java中實現基於其密鑰排序的MaxHeap。 每個鍵也與一個值相關聯。 當我嘗試運行程序時,出現異常: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LMaxHeap$Obj;
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LMaxHeap$Obj;
編輯此行上引發異常: o = (Obj[])new Object[n+1];
我該如何解決我的問題?
這是我的代碼:
public class MaxHeap<Key,Value> {
Obj [] o;
int N;
int size;
private Comparator<Key> comparator;
public MaxHeap(int n){
o = (Obj[])new Object[n+1];
size =0;
N = n;
}
public class Obj{
Key k;
Value v;
public Obj(Key k, Value v){
this.k = k;
this.v = v;
}
}
void push(Key k, Value v) {
Obj temp = new Obj(k,v);
o[++size] = temp;
swim(size);
}
Obj pop() {
Obj del = o[1];
Obj temp = o[1];
o[1] = o[size];
o[size--] = temp;
sink(1);
return del;
}
boolean isLess(int i, int j){
return ((Comparable<Key>) o[i].k).compareTo(o[j].k) < 0;
}
void swim(int index){
Obj temp;
while(index > 1 && isLess(index/2,index)){
temp = o[index];
o[index] = o[index/2];
o[index/2] = temp;
index = index/2;
}
}
void sink(int index){
int i;
Obj temp;
while(2*index <= size){
i = 2*index;
if(i < size && isLess(i, i+1))
i++;
if(!isLess(index,i))
break;
temp = o[index];
o[index] = o[i];
o[i] = temp;
index = i;
}
}
}
查看例外情況,它將給出一個行號。 查看您要投射到/來自的內容。 您可以在投射之前使用instanceof運算符進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.