PriorityQueue
Priority Queue is a class that is defined in the java collection framework and implements the Queue interface. It also follows FIFO order but in this case elements in the queue are placed according to their priorities.
Syntax to declare Priority Queue:
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Advantages:
- Searching of data is easy as they are placed according to their priority.
- PriorityQueues are more efficiently organized
Disadvantages:
- Performing insertion operations on a priority queue take more time as they need to find the positions of elements according to their priority.
Here let us see whether we can use Queue or priority queue when we are using priority queue.
Case – 1:
PriorityQueue<Integer> pq = new PriorityQueue<>();
Advantages: By declaring the priority queue as priority queue we can quickly access the highest item with a time complexity of just O(1).
Disadvantages: Enqueue and dequeue operations on the priority queue are slow and also have a time complexity of O(log n).
Case – 2:
Queue<Integer> q = new PriorityQueue<>();
Advantages: By defining a priority queue as Queue we can change the actual implementation with a single line.
Disadvantages: In some cases, it will generate errors if our code includes priority functionalities where prioritization methods are absent because of declaring the priority queue as Queue.