我正在Java中实现一个基于其键排序的MaxHeap。每个键也与一个值相关联。当我尝试运行我的程序时,我得到一个异常: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;
}
}
}
答案 0 :(得分:0)
查看它将给出行号的异常。看看你要投掷什么。您可以在转换之前使用instanceof运算符进行测试。