Create an array of Queues in Java

22,643

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...

Share:
22,643
switz
Author by

switz

Updated on July 09, 2022

Comments

  • switz
    switz almost 2 years

    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);
    }
    
  • switz
    switz over 12 years
    Perfect. I knew it was something small, but it was bugging me. +1 as you gave the code to do it.