Java Program to Implement PriorityQueue API
A PriorityQueue is a linear data structure in which the elements are ordered according to their natural ordering or by some custom comparator provided at the queue at construction time. In PriorityQueue, the front of the queue points to the least element, and the rear points to the greatest element according to the natural Ordering. For alphabetical PriorityQueue, their ASCII values will be considered for ordering.
Some important characteristics of PriorityQueue are as follows:
- It does not allow the null elements to be inserted.
- It is an unbounded Queue that means its size can be expanded.
- It inherits the classes like Object, Abstract Collection, AbstractQueue.
- It is not thread-safe.
- It cannot be created for non-comparable objects.
Time Complexities of various operations:
- Insertion and deletion are f order O(log(n))
- remove() and contains() method is of order O(n)
- Retrieval operations are the fastest which are of order O(1)
The PriorityQueue class inherits Queue Interface and all of its methods. PriorityQueue API implements serializable, Iterable, Collection, and Queue which can be perceived from the architecture shown below.
Serializable, Iterable<E>, Collection<E>, Queue<E>
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Parameter: E — The type of elements held in this queue.
Method Type Description add(E e) boolean Inserts an element e to the PriorityQueue clear() void Removes all the elements from the PriorityQueue contains(Object O) boolean Return true if it contains the specified element iterator() Iterator<E> Returns an iterator over all the elements remove(Object o) boolean Removes the specified element from the Queue comparator() Comparator<E> Returns the custom comparator used to order th elements toArray() Object Returns an array that contains all the elements in the PriorityQueue. peek() <E> Return the head of the PriorityQueue without deleting the element from the Queue poll() <E> Removes and returns the head of the queue. Returns null if the queue is empty. spliterator() Spliterator<E> Creates a late-binding and fail-fast Spliterator over the elements in the PriorityQueue.
PriorityQueue Head:12 PriorityQueue contents: 12 19 78 89 67 PriorityQueue contents:19 67 78 89 The queue has 7 = true PriorityQueue contents:2 7 5 9
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.