Create an array of Queues in Java Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Create an array of Queues in Java without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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…

We are here to answer your question about Create an array of Queues in Java - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji