0

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;

}

}
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
  • Where are you calling add method? Can you paste your main method as well? – SMA May 31 '15 at 18:17
  • Where do you "implement" this? Please show all code, including the stack trace. – markspace May 31 '15 at 18:17
  • 3
    Look your no-args constructor. You need to initialize the array in it with a default size, otherwise `heapArr` is null. – Alexis C. May 31 '15 at 18:17
  • When you get this more working, you should ask about Java generics. I.e. probably you should use `public class Heap> {...` – markspace May 31 '15 at 18:21

0 Answers0