VOOZH about

URL: https://www.geeksforgeeks.org/java/priorityblockingqueue-add-method-in-java/

⇱ PriorityBlockingQueue add() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PriorityBlockingQueue add() Method in Java

Last Updated : 13 May, 2022

The add(E e) method of PriorityBlockingQueue inserts the element passed as a parameter to the method at the tail of this PriorityBlockingQueue. This method returns true if the adding of the element is successful. Else it returns false. 

Syntax:

public boolean add(E e)

Parameter: This method takes a mandatory parameter e which is the element to be inserted in PriorityBlockingQueue. 

Returns: This method returns a boolean response. It returns true if the adding of the element is successful, else it returns false

Exception: This method throws following exceptions:

  • ClassCastException: if the element passed as parameter cannot be compared to the element contained by queue to keep priority queue's ordering.
  • NullPointerException: if the element passed as parameter is null.

Below program illustrate  add() method of PriorityBlockingQueue: 

Example 1: 

Output:
After Adding Some Numbers
PriorityBlockingQueue:[526734, 84879456, 4586415]

After adding Some More Numbers
PriorityBlockingQueue:[156116, 526734, 4586415, 84879456, 61651191]

Example 2: To demonstrate NullPointerException thrown by add() method. 

Output:
Exception when adding null: java.lang.NullPointerException

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#add-E-

Comment