有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaI编写了一个通用的有序数组类,在比较元素时,insert方法出现空指针错误

public class GenericOrderedArray<T extends Comparable<T>> {

private T[] a;
private int n;

public GenericOrderedArray(Class<T> clazz, int max) {
    a = (T[]) Array.newInstance(clazz, max);
    n = 0;
}

public void insert(T value) {
    int j;
    for (j = 0; j < n; j++)
                    //this is where error goes ,the compare to method throws a null pointer exception
        if (a[j] != null && a[j].compareTo(value) > 0)
            break;
    for (int k = n; k < j; k--)
        a[k] = a[k - 1];
    a[j] = value;
    n++;
}

public boolean delete(T value) {
    boolean result = false;
    int hit = find(value);
    if (hit == -1)
        return result;
    else {
        for (int i = hit; i < n; i++) {
            a[i] = a[i + 1];
        }
        n--;
    }
    return result;
}


    //binary search implements find method 
public int find(T value) {
    int lowerBound = 0;
    int upperBound = n - 1;
    int curIn;
    while (true) {
        curIn = (lowerBound + upperBound) / 2;
        if (a[curIn].equals(value))
            return curIn;
        else if (lowerBound > upperBound) {
            return -1;
        } else {
            if (a[curIn].compareTo(value) < 0)
                lowerBound = curIn + 1;
            else {
                upperBound = curIn - 1;
            }
        }
    }

}

public static void main(String[] args) {
    int max = 100;
    GenericOrderedArray<Integer> ints = new GenericOrderedArray<>(Integer.class, max);
    ints.insert(2);
    ints.insert(4);
    ints.insert(1);
}
}

数组比较每个元素,并将较小的元素移动到较低的索引。这可能是个假问题。比较元素时会出现异常,但我不知道为什么


共 (4) 个答案

  1. # 1 楼答案

    我的猜测是,当你插入第一个元素时,你正在比较a[j]和要插入的元素。但是,由于第一次插入元素时[0]处没有元素,因此会抛出NPE

    如果您的第一个元素是insert,那么应该先插入NULL。如果[0]=NULL,则只需在其中插入元素,否则继续使用compare语句

  2. # 2 楼答案

    你的代码对我有用。在Linux、jdk6和jdk7上试用过
    一般来说,compare方法在代码中抛出NPE的唯一方式是将null作为值传递,因为要检查[j]是否为null。确保没有将null传递给insert方法

  3. # 3 楼答案

    如果您查看Comparable接口文档。它说:

    The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.(This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

    因此,如果您试图将任何内容与null进行比较,则应该有一个NPE

  4. # 4 楼答案

    for (int k = n; **k < j**; k--)
        a[k] = a[k - 1];
    

    我认为你应该有k>;j