Java Utility Library

Java PriorityQueue - add() Method



The java.util.PriorityQueue.add() method is used to insert the specified element into this priority queue.

Syntax

public boolean add(E element)

Here, E is the type of element maintained by the container.


Parameters

element Specify element which need to be inserted in the priority queue.

Return Value

true.

Exception

  • Throws ClassCastException, if the specified element cannot be compared with elements currently in this priority queue according to the priority queue's ordering.
  • Throws NullPointerException, if the specified element is null.

Example:

In the example below, the java.util.PriorityQueue.add() method is used to insert the specified element into this priority queue.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a priority queue
    PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>();

    //populating the priority queue using add method
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(30);
    PQueue.add(40);
    PQueue.add(50);

    //printing the priority queue
    System.out.println("PQueue contains: " + PQueue);   
  }
}

The output of the above code will be:

PQueue contains: [10, 20, 30, 40, 50]

❮ Java.util - PriorityQueue