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

In this shot, we will learn how to use the PriorityQueue.offer() method in Java.

Introduction

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

The PriorityQueue.offer() method is used to insert a particular element in the PriorityQueue.

Syntax

The syntax of the PriorityQueue.offer() method is given below:

public boolean offer(E element);

Parameters

The PriorityQueue.offer() accepts one parameter:

  • Element: The element that needs to be inserted into PriorityQueue.

Return value

The PriorityQueue.offer() method returns a boolean value:

  • True: If the specified element is inserted in the PriorityQueue.
  • False: If the specified element is not inserted in the PriorityQueue.

Code

Let us have a look at the code now.

import java.util.*;
class Main
{
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
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);
pq.offer(45);
System.out.println("Elements in the priority queue after adding 45 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.

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

  • In line 16, we display the elements present in the priority queue.

  • In line 18, we use the PriorityQueue.offer() method to add an element.

  • Finally, in line 20, we print the priority queue and verify that the element has been inserted.

So, in this way, we can use the PriorityQueue.offer() method to insert an element in the priority queue data structure in Java.

Free Resources