4

I'm writing my own PriorityQueue class and I have:

private Queue<E>[] queues;


public PriorityQueue(int maxSize) {
  queues = new Queue[maxSize+1]; 
  size = maxSize;
}

This compiles, but when I call .add on the priorityQueue I get this error:

java.lang.NullPointerException
    at PriorityQueue.add(PriorityQueue.java:13)

Here's add:

public void add(E item, int priority) {
  queues[priority].offer(item);
}
0

5 Answers 5

6

you need to initialize your queues:

public PriorityQueue(int maxSize) {
  queues = new Queue[maxSize+1]; 
  size = maxSize;
  for(int i = 0; i <= maxSize; i++) 
    queues[i] = new LinkedList<E>(); 
}

You can pick whatever Queue implementation you want, I just picked LinkedList because it popped in my head first...

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. I knew it was something small, but it was bugging me. +1 as you gave the code to do it.
0

When you do this:

 queues = new Queue[maxSize+1]; 

you create an array of size maxSize+1 but each element of the array is still null. You have to iterate over the array and place a Queue object in each position before you can add to it.

Comments

0

You create a new array, but you never initialize the elements of queues to be a Queue. By default, all elements of queues are null until you initialize them.

Comments

0

queues[priority] returns a queue, on which you're calling .offer(). Because you're not initializing the elements of the array, you're calling .offer() on a null reference, which is causing your error.

Comments

0

You haven't initialized the array of queues to have any queues.

You need to put queues into the array. Also not sure why you add an additional queue unless you're just trying to pretend arrays aren't 0-based.

public PriorityQueue(int maxSize) {
    queues = new Queue<E>[maxSize+1]; 
    for (int i = 0; i < maxSize + 1; i++) {
        queues[i] = new LinkedList<E>(); // Or whatever implementation you're using.
    }
    size = maxSize;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.