Create an array of Queues in Java

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);
}

Answer

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…

Leave a Reply

Your email address will not be published. Required fields are marked *