What is the PriorityQueue.isEmpty() method in Java?
In this shot, we will learn how to use the PriorityQueue.isEmpty() method in Java.
Introduction
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.
Syntax
The syntax of the PriorityQueue.isEmpty() method is given below:
public boolean isEmpty();
Parameters
The PriorityQueue.isEmpty() method does not accept any parameters.
Return value
The PriorityQueue.isEmpty() method returns a boolean value:
-
True: If thePriorityQueueis empty. -
False: If thePriorityQueueis not empty.
Code
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.");}}
Explanation
-
In line 1, we import the required package.
-
In line 2, we make a
Mainclass. -
In line 4, we make a
main()function. -
In line 6, we declare a
PriorityQueuethat consists of integer type elements. -
From lines 8 to 11, we call the
isEmpty()method to check whether thePriorityQueueis 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 thePriorityQueue. -
From lines 17 to 20, we check whether the
PriorityQueueis 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.