java - 使用键、值对实现 MaxHeap

标签 java data-structures noclassdeffounderror max-heap

我正在 Java 中实现一个 MaxHeap,它根据其键进行排序。每个键还与一个值相关联。当我尝试运行程序时,出现异常:Exception in thread "main"java.lang.ClassCastException: [Ljava.lang.Object;无法转换为 [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运算符进行测试。

关于java - 使用键、值对实现 MaxHeap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655588/

相关文章:

java - 更新属性是否需要在主线程上进行?

java - Spring session 惰性反序列化

c - 一个变量只能存储一个值,如何存储多个值?

java - JWebBrowser NoClassDefFoundError 错误

java - Jdeveloper 启动时错误 "java.lang.NoClassDefFoundError: Could not initialize class oracle.dbtools.raptor.config.DBConfig"

android - Android 上的 OSGi (Felix) : NoClassDefFoundError: sun/reflect/ConstructorAccessorImpl

java - Spring Batch在步骤内访问作业参数

java - 使用 bufferedimage 重新绘制图像

database - 在 Redis 中搜索与给定模式不匹配的键

mysql - 设计复杂的 SQL 结构