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);
}
}
该数组比较每个元素并将移动的较小元素放到较低的索引中。这可能是一个愚蠢的问题。比较元素时发生异常,但我不知道为什么。