offer(K): This method is available in java.util.PriorityQueue class of Java.
Syntax:
boolean java.util.PriorityQueue.offer(K e)
This method takes one argument. This method inserts the specified element into this priority queue.
Parameters: One parameter is required for this method.
e: the element to add.
Returns: true.
Throws:
1. ClassCastException - if the specified element cannot be compared with elements currently in this priority queue according to the priority queue's ordering.
2. NullPointerException - if the specified element is null
Approach 1: When no exception
Java
import java.util.PriorityQueue;public class PriorityQueueoffer {public static void main(String[] args) {PriorityQueue<Integer> priorityQueue =new PriorityQueue<Integer>();priorityQueue.add(12);priorityQueue.add(5);priorityQueue.add(10);priorityQueue.add(2);System.out.println(priorityQueue.offer(12));}}
Output:
true
Approach 2: NullPointerException
Java
import java.util.PriorityQueue;public class PriorityQueueoffer {public static void main(String[] args) {PriorityQueue<Integer> priorityQueue =new PriorityQueue<Integer>();priorityQueue.add(12);priorityQueue.add(5);priorityQueue.add(10);priorityQueue.add(2);System.out.println(priorityQueue.offer(null));}}
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.PriorityQueue.offer(PriorityQueue.java:325)
No comments:
Post a Comment