java.util package.
package java.util;
public class PriorityQueue<E> implements java.io.Serializable
{
// Constructors
// Methods
// Fields
}
PriorityQueue Class
PriorityQueue class:
| Sr. No. | Constructor | Description |
|---|---|---|
| 1 | PriorityQueue() |
Constructs a PriorityQueue with default initial capacity (11) and natural ordering of elements. |
| 2 | PriorityQueue(int initialCapacity) |
Constructs a PriorityQueue with the specified initial capacity and natural ordering of elements. |
| 3 | PriorityQueue(Collection<? extends E> c) |
Constructs a PriorityQueue containing the elements of the specified collection, ordered according to their natural ordering. |
| 4 | PriorityQueue(int initialCapacity, Comparator<? super E> comparator) |
Constructs a PriorityQueue with the specified initial capacity and the specified comparator to order the elements. |
PriorityQueue Class
PriorityQueue class:
| Sr. No. | Method | Description |
|---|---|---|
| 1 | boolean offer(E e) |
Adds the specified element to this priority queue. Equivalent to add(), but returns false if element cannot be added. |
| 2 | E poll() |
Retrieves and removes the head (highest priority) of this queue, or returns null if this queue is empty. |
| 3 | E peek() |
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. |
| 4 | boolean remove(Object o) |
Removes a single instance of the specified element from this queue, if it is present. |
| 5 | boolean contains(Object o) |
Returns true if this queue contains the specified element. |
PriorityQueue inherits all methods from Queue and Collection interfaces.
null elements.
Comparator.
PriorityQueue with unordered integers.
import java.util.PriorityQueue;
public class PriorityQueueDemo
{
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<>();
// Adding elements in unordered way
pq.add(20);
pq.add(50);
pq.add(30);
pq.add(10);
pq.add(40);
pq.add(70);
pq.add(60);
System.out.println("PriorityQueue printed directly: " + pq);
System.out.println("-------------------------");
System.out.println("Polling elements (retrieved in sorted order):");
while(!pq.isEmpty())
{
System.out.println(pq.poll());
}
}
}
PriorityQueue printed directly: [10, 20, 30, 50, 40, 70, 60] ------------------------- Polling elements (retrieved in sorted order): 10 20 30 40 50 60 70
poll() removes and returns the smallest element each time.PriorityQueue Class:
poll() or peek() based on priority.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.