PriorityQueue offer() trong java dùng để thêm một phần tử vào PriorityQueue. Lưu ú nếu bạn offer phần tử null sẽ gây ra NullPointerException.
Syntax
public boolean offer(E e)
Parameter: phần tử được thêm vào PriorityQueue
Return: Trả về true nếu thêm thành công, ngược lại false.
Ví dụ
import java.util.PriorityQueue;
public class Main {
public static void main(String args[])
{
// Creating an empty PriorityQueue
PriorityQueue<String> queue = new PriorityQueue<String>();
// Use add() method to add elements into the Queue
queue.offer("Welcome");
queue.offer("To");
queue.offer("Share");
queue.offer("Programming");
System.out.println("PriorityQueue: " + queue);
}
}
Output: PriorityQueue: [Programming, Share, To, Welcome]
Ví dụ 2: NullPointerException
import java.util.PriorityQueue;
public class Main {
public static void main(String args[])
{
// Creating an empty PriorityQueue
PriorityQueue<String> queue = new PriorityQueue<String>();
// Use add() method to add elements into the Queue
queue.offer("Welcome");
queue.offer("To");
queue.offer("Share");
queue.offer(null);
System.out.println("PriorityQueue: " + queue);
}
}
Output: Exception in thread “main” java.lang.NullPointerException