In this shot, we will learn how to use the PriorityQueue.isEmpty()
method in Java.
The PriorityQueue.isEmpty()
method is present in the PriorityQueue
class inside the java.util
package. This method is inherited from the AbstractCollection
class.
PriorityQueue.isEmpty()
is used to check whether the PriorityQueue
is empty or not.
The syntax of the PriorityQueue.isEmpty()
method is given below:
public boolean isEmpty();
The PriorityQueue.isEmpty()
method does not accept any parameters.
The PriorityQueue.isEmpty()
method returns a boolean value:
True
: If the PriorityQueue
is empty.
False
: If the PriorityQueue
is not empty.
Let us have a look at the code now.
import java.util.*;class Main{public static void main(String[] args){PriorityQueue<Integer> p = new PriorityQueue<Integer>();if(p.isEmpty())System.out.println("Priority Queue is empty.");elseSystem.out.println("Priority Queue is not empty.");p.add(2);p.add(28);p.add(6);if(p.isEmpty())System.out.println("Priority Queue is empty.");elseSystem.out.println("Priority Queue is not empty.");}}
In line 1, we import the required package.
In line 2, we make a Main
class.
In line 4, we make a main()
function.
In line 6, we declare a PriorityQueue
that consists of integer type elements.
From lines 8 to 11, we call the isEmpty()
method to check whether the PriorityQueue
is empty or not and display the message accordingly. In the output, we can see that the priority queue is empty.
From lines 13 to 15, we use the PriorityQueue.add()
method to insert the elements in the PriorityQueue
.
From lines 17 to 20, we check whether the PriorityQueue
is empty or not and display the message accordingly. In the output, we can see that the priority queue is not empty as we have added elements in the priority queue.
So, in this way, we can use the PriorityQueue.isEmpty()
method to check whether a priority queue is empty or not in Java.