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);
}
}
配列は各要素を比較し、小さい方の要素を低い方のインデックスに移動します。これはダミーの質問かもしれません。要素を比較すると例外が発生しますが、その理由がわかりません。