我创建了一个Heap类,它使用从Comparable类扩展的E general类型泛型。在isEmpty
方法中,它检查第一个元素是否为空。
但是当我实现它时,isEmpty
和add
方法会发生NullPointerException。我该如何解决?
public class Heap<E extends Comparable<E>> {
private E[] heapArr ;
private int size = 3 ;
public Heap(){
}
public Heap(E[] a){
this.heapArr = a;
size = a.length;
}
public boolean isEmpty(){
if(heapArr[0] == null)
return true;
else
return false;
}
public void add(E element){
if(isEmpty()){
heapArr[0] = element;
}
else{
int parent = (size-1)/2;
while((int) element > (int) heapArr[parent]){
heapArr[parent] = element;
parent = (parent-1)/2;
}
}
}
public E remove(){
heapArr[0] = heapArr[size];
size = (size - 1);
int x = 0;
TricklingDown(heapArr, x);
return heapArr[0];
}
public int max(E e1, E e2){
if((int) e1 > (int) e2){
return (int) e1;
}
else
return (int) e2;
}
public void swap(E e, int x){
heapArr[x] = e;
}
public int TricklingDown(E[] heapArr1, int x){
int leftChild = (2*x +1);
int rightChild = (2*x +2);
int largerChild = 0;
while((int) heapArr1[x] < (int) heapArr1[leftChild] || (int) heapArr1[x] < (int) heapArr1[rightChild]){
largerChild = max(heapArr1[leftChild], heapArr1[rightChild]);
swap(heapArr1[x], largerChild);
x ++;
}
if(largerChild == leftChild){
return leftChild;
}
else
return rightChild;
}
}