Skip to content

Latest commit

 

History

History
51 lines (44 loc) · 1.91 KB

PriorityQueue.md

File metadata and controls

51 lines (44 loc) · 1.91 KB

PriorityQueue

A PriorityQueue is used when the objects are supposed to be processed based on the priority. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering

Important points on Priority Queue

  • PriorityQueue doesn’t permit null.
  • We can’t create PriorityQueue of Objects that are non-comparable
  • The head of this queue is the least element with respect to the specified ordering.
  • It provides O(log(n)) time for add and poll methods.

Constructors

  • PriorityQueue pq = new PriorityQueue();

  • PriorityQueue pq = new PriorityQueue(int initialCapacity);

  • PriorityQueue pq = new PriorityQueue(Collection c);

NOTE : By default, PriorityQueue implements MinHeap. To implement MaxHeap, send Collections.reverseOrder() ( Comparator) to the PriorityQueue constructor.

Methods in PriorityQueue

Method Description
public boolean add(E e) Inserts the specified element into this priority queue.
public E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
public boolean contains(Object o) Returns true if this queue contains the specified element.
More formally, returns true if and only if this queue contains at least one element e
such that o.equals(e).
public E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
public int size() Returns the number of elements in this collection. If this collection contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.