What is the PriorityQueue.size() method in Java?
In this shot, we will learn how to use the PriorityQueue.size() method in Java.
Introduction
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.
Syntax
The syntax of the PriorityQueue.size() function is given below:
public int size();
Parameters
The PriorityQueue.size() method does not accept any parameters.
Return value
The PriorityQueue.size() method returns an integer value that denotes the number of elements in the PriorityQueue.
Code
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());}}
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. -
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 thePriorityQueue. -
In line 18, we use the
PriorityQueue.size()method to display the number of elements present in thePriorityQueue.