Search code examples
javanullpointerexceptionpriority-queue

Priority Queue java


Sorry to bother, however, a friend and I have been sitting at this problem for a while and we seem to be quite stuck. We have to create a PriorityQueue class which interacts with an Elements class. The idea in the main method is to put elements according to a priority into the queue and then return those elements in the right order. Now, if we try to use this code, we get an java.lang.NullPointerException. Our getPriority looks like this:

public int getPriority() {
 return priority;
}

We really don't know where the Null Pointer Exception comes from...

public class PriorityQueue {
 static final int SIZE = 32;
 Element[] q = new Element[SIZE];
 int len;
 int head = 31;
 int tail = 31;

 // Insert an element into the queue according to its priority
 boolean put(Element x) {
  if (head == 0) { return false;}    else {
   for (int g=31; g >= 0; g--) {
    if (q[g].getPriority() == x.getPriority()||(q[g].getPriority() < x.getPriority() && q[g-1].getPriority() > x.getPriority())) {
     for (int y=g; y >= head; y--) {
      Element z = q[y];
      q[y] = x;
      q[y-1] = z;
     }
    }
   }
  } head--;
return true;
}

// Return the element with the highest priority from the queue
Element get() {
return q[head];
}

// Return the queue length
int length() {
return q.length;
}

// Print the queue contents
public String toString() {
    return q.toString();
}
}

Thank you very much in advance.


Solution

  • So you have an empty array of Elements and you do somethin like this:

     for (int g=31; g >= 0; g--) {
        if (q[g].getPriority() == x.getPriority()||(q[g].getPriority() < x.getPriority() && q[g-1].getPriority() > x.getPriority())) {
    

    wouldnt q[g] be null here?