What is the PriorityQueue.add() method in Java?

In this shot, we’ll learn how to use the PriorityQueue.add() method in Java.

Introduction

PriorityQueue.add() is used to insert a particular element into the PriorityQueue.

The PriorityQueue.add() method is present in the PriorityQueue class inside the java.util package.

Syntax

The syntax of the PriorityQueue.add() function is given below:

public boolean add(E element);

Parameters

The PriorityQueue.add() method accepts one parameter:

  • Element: The element to be inserted into PriorityQueue.

Return value

The PriorityQueue.add() method returns a Boolean value. PriorityQueue.add() returns true if the specified element is inserted in the PriorityQueue. Otherwise, it returns false.

Example

Let’s take a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
System.out.println("Elements in the priority queue are: " + pq);
pq.add(2);
pq.add(28);
pq.add(6);
pq.add(80);
pq.add(28);
pq.add(7);
pq.add(15);
System.out.println("Elements in the priority queue are: " + pq);
}
}

Explanation

  • 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 elements present in the queue. As of now, there are no elements.

  • From lines 10 to 16, we use the PriorityQueue.add() method to insert the elements in the PriorityQueue.

  • In line 18, we display the elements present in the PriorityQueue. Now, our elements are added to the priority queue.

In this way, we can use the PriorityQueue.add() method in Java to insert elements in the priority queue data structure.

Free Resources