I create a Heap class which uses E general type generics extends from Comparable class. In the isEmpty
method it checks whether the first element is empty or not.
But when I implement it, a NullPointerException occurs at isEmpty
and add
methods. How can I fix it ?
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;
}
}