Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
Using the PriorityQueue.add() method in Java

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring