我认为这个方法应该可行,但是当我尝试使用remove方法时,我一直得到nullpointer异常。
我已经向堆中添加了8个内容,然后使用remove()
方法逐个打印它们。在第二个每次我得到一个空指针异常,但我不明白为什么?所以,我在for循环中尝试了System.out.println(example.remove());
,但它会打印一件事然后给我一个空指针异常。我的IDE说空指针来自remove,然后来自percolate,然后来自compare。
如何解决此问题?
public class GenericHeap<E> {
private int size;
int capacity = 10;
public E[] heap;
Comparator mycomparator;
public GenericHeap(Comparator c) {
this.size = 0;
heap = (E[]) new Object[capacity];
mycomparator = c;
}
public E remove() {
E returnval = heap[1];
heap[1] = heap[size];
size--;
this.pop();
this.percolatedown(1);
return returnval;
}
private void pop() {
E[] temp = (E[]) new Object[capacity];
System.arraycopy(heap, 0, temp, 0, size);
heap = temp;
}
private void percolatedown(int i) {
while (i * 2 <= size) {
int kid = minchild(i);
if (mycomparator.compare(this.heap[i], this.heap[kid]) == 1) {
E temp = this.heap[i];
this.heap[i] = this.heap[kid];
this.heap[kid] = temp;
}
i = kid;
}
}
private int minchild(int i) {
if ((i * 2) + 1 >= size) {
return i * 2;
} else {
if (mycomparator.compare(heap[i * 2], heap[(i * 2) + 1]) == -1) {
return i * 2;
} else if (mycomparator.compare(heap[i * 2], heap[(i * 2) + 1]) >0) {
return i * 2 + 1;
}
}
return i*2;
}
}
比较器类:
public class StringComparator implements Comparator <String> {
@Override
public int compare(String t, String t1) {
if (t.length() > t1.length()) { // null pointer here
return 1;
} else if (t.length()<t1.length()){
return -1;
}
if (t.compareTo(t1)<0) {
return 1;
}
if(t1.compareTo(t1)>0) {
return -1;
}
return 0;
}
}
我得到了这个例外:
Exception in thread "main" java.lang.NullPointerException
at hw10.StringComparator.compare(StringComparator.java:10)
at hw10.StringComparator.compare(StringComparator.java:6)
at hw10.GenericHeap.percolatedown(GenericHeap.java:82)
at hw10.GenericHeap.remove(GenericHeap.java:53)
at hw10.Tester.main(Tester.java:62)
Java结果:1
答案 0 :(得分:1)
当你尝试这个:System.out.println(example.remove());在for循环中,只得到第一个示例的结果,第二个示例得到NullPponterException,这意味着第二个示例为null。
试试这个:
List<GenericHeap> genericHeapList = new ArrayList<GenericHeap>(...)
for(GenericHeap example : genericHeapList){
if(example != null){
System.out.println(example.remove());
}
}