In this shot, we will learn how to use the PriorityQueue.size()
method in Java.
The PriorityQueue.size()
method obtains the number of elements present in the PriorityQueue
.
The PriorityQueue.size()
method is present in the PriorityQueue
class inside the java.util
package.
The syntax of the PriorityQueue.size()
function is given below:
public int size();
The PriorityQueue.size()
method does not accept any parameters.
The PriorityQueue.size()
method returns an integer value that denotes the number of elements in the PriorityQueue
.
Let us have a look at the code below.
import java.util.*;class Main{public static void main(String[] args){PriorityQueue<Integer> pq = new PriorityQueue<Integer>();System.out.println("Number of elements in the priority queue are: " + pq.size());pq.add(2);pq.add(28);pq.add(6);pq.add(80);pq.add(28);pq.add(7);pq.add(15);System.out.println("Number of elements in the priority queue are: "+pq.size());}}
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.
In line 8, we print the current number of elements in the priority queue. Here, the output comes to .
From lines 10 to 16, we use the PriorityQueue.add()
method to insert the elements in the PriorityQueue
.
In line 18, we use the PriorityQueue.size()
method to display the number of elements present in the PriorityQueue
.