PriorityBlockingQueue的put(E e)方法用於將元素添加到此隊列中。此方法將指定的元素插入此優先級隊列。由於隊列是無界的,因此永遠不會阻止此方法。
用法:
public void put(E e)
參數:此方法接受強製參數e,該參數是要插入PriorityBlockingQueue的元素。
返回值:該方法不返回任何內容。
異常:此方法引發以下異常:
- ClassCastException–如果無法根據優先級隊列的順序將指定的元素與優先級隊列中的當前元素進行比較。
- NullPointerException –如果指定的元素為null。
下麵的程序說明PriorityBlockingQueue中的put()方法:
示例1:
// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
import java.util.concurrent.PriorityBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// create object of PriorityBlockingQueue
PriorityBlockingQueue<Integer> pbq
= new PriorityBlockingQueue<Integer>();
// Add element using put() method
pbq.put(1);
pbq.put(2);
pbq.put(3);
pbq.put(4);
// print elements of queue
System.out.println("Queue: " + pbq);
}
}
輸出:
Queue: [1, 2, 3, 4]
示例2:演示NullPointerException
// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
import java.util.concurrent.PriorityBlockingQueue;
public class GFG {
public static void main(String[] args)
{
// create object of PriorityBlockingQueue
PriorityBlockingQueue<String> pbq
= new PriorityBlockingQueue<String>();
// try to put null value in put method
try {
pbq.put(null);
}
catch (Exception e) {
// print error details
System.out.println("Exception: " + e);
}
}
}
輸出:
Exception: java.lang.NullPointerException
相關用法
- Java PriorityBlockingQueue contains()用法及代碼示例
- Java PriorityBlockingQueue add()用法及代碼示例
- Java PriorityBlockingQueue take()用法及代碼示例
- Java PriorityBlockingQueue toString()用法及代碼示例
- Java PriorityBlockingQueue comparator()用法及代碼示例
- Java PriorityBlockingQueue size()用法及代碼示例
- Java PriorityBlockingQueue remainingCapacity()用法及代碼示例
- Java PriorityBlockingQueue remove()用法及代碼示例
- Java PriorityBlockingQueue iterator()用法及代碼示例
- Java PriorityBlockingQueue peek()用法及代碼示例
- Java PriorityBlockingQueue spliterator()用法及代碼示例
- Java PriorityBlockingQueue offer()用法及代碼示例
- Java PriorityBlockingQueue toArray()用法及代碼示例
- Java PriorityBlockingQueue poll()用法及代碼示例
- Java PriorityBlockingQueue clear()用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 PriorityBlockingQueue put() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。