Java Utility Library

Java PriorityQueue - clear() Method



The java.util.PriorityQueue.clear() method is used to clear all elements of the priority queue. This method makes the priority queue empty with a size of zero.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.PriorityQueue.clear() method is used to clear all elements of the priority queue called PQueue.

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
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(30);
    PQueue.add(40);
    PQueue.add(50);

    //printing the priority queue
    System.out.println("Before applying clear() method.");
    System.out.println("PQueue contains: " + PQueue);

    PQueue.clear();

    //printing the priority queue
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("PQueue contains: " + PQueue);   
  }
}

The output of the above code will be:

Before applying clear() method.
PQueue contains: [10, 20, 30, 40, 50]

After applying clear() method.
PQueue contains: []

❮ Java.util - PriorityQueue