[英]Java: NullPointerException when trying to add object to BlockingQueue?
[英]NullPointerException when trying to add an object to a PriorityQueue
嘗試將對象添加到優先級隊列時,我不斷收到空指針異常
我初始化隊列:
private PriorityQueue<NodeObject> nodes;
在這里我嘗試添加到它:
NodeObject childNode = new NodeObject(child, 1);
nodes.add(childNode);
為什么這不起作用? 我知道我的NodeObject不是null,因為我在添加它之前創建它。
您尚未初始化隊列。
nodes = new SomePriorityQueue();
問題是您忘記初始化優先級隊列nodes
。 將其更改為:
private PriorityQueue<NodeObject> nodes = new PriorityQueue<NodeObject>();
或者在每個構造函數中顯式分配nodes
(如nodes = new PriorityQueue<NodeObject>();
)。 請記住,在Java中,任何非原語的類型實際上都是一個隱式指針,因此當指針nodes
初始化為null
,它尚未初始化為指向某個東西。
您實際上並沒有創建優先級隊列; nodes == null
。 當您嘗試調用nodes.add
時,這會導致拋出NullPointerException
。
解決此問題的方法是實際構建PriorityQueue<NodeObject>
,並將其引用分配給nodes
。 您可以在聲明中執行以下操作:
private PriorityQueue<NodeObject> nodes = new PriorityQueue<NodeObject>();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- 在創建時,每個類變量,實例變量或數組組件都使用默認值進行初始化:
- 對於所有引用類型,默認值為
null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.