2012-10-22 88 views
0

我一直在努力擺脫調用的代碼行時出現NullPointerException異常的:無法擺脫NullPointerException異常爲比較

if (priorityComparator.compare(temp.next.value, newNode.value) >= 0) 

完整的代碼是:

public class HeaderLinkedPriorityQueue<E> extends 
     AbstractPriorityQueue<E> implements PriorityQueue<E> { 

    //Some other methods, constructors etc. 

public boolean add (E e) { 

    ListNode<E> temp = highest; 


    ListNode<E> newNode = new ListNode<E>(e, null); 

    if (temp.next == null){ 
     //first node in a list. 
     temp.next = newNode; 
     objectCount++; 
     return true; 
    } 

    //if the value of the first element following the header node is greater than the newNode add to back. 
    if (priorityComparator.compare(temp.next.value, newNode.value) >= 0) { 
     temp.next.next = newNode; 
     objectCount++; 
    } 
    else { 
     //add before the first node in the list. have temp.next point to newNode and have newNode point to the old temp.next. 
     newNode.next = temp.next; 
     temp.next = newNode; 
     objectCount++; 
    } 
    return true; 
} 

//class variables. 
private ListNode<E>   highest  = new ListNode(null, null); 
private int     objectCount = 0; 
private Comparator<? super E> priorityComparator; 

我沒有看到任何錯誤的參數,所以我真的難倒了。我怎樣才能解決這個問題?

+1

檢查temp.next.value,newNode.value爲空或不 –

+3

我會承擔,要麼priorityComparator爲空或temp.next.value爲空或newNode .value爲null。在調試器中查看變量。實際的錯誤信息說什麼? –

+1

打印或調試程序以找出錯誤。任何人:priorityComparator,temp,temp.next或newNode。根據實施情況,也可以是temp.next.value或newNow.value。 – John3136

回答

5

看起來你沒有初始化你的PriorityComparator。

private Comparator<? super E> priorityComparator; 

應該像

private Comparator<? super E> priorityComparator = new PriorityComparator(); 
+0

其實不是這樣的:P – nitiger

+0

@nitiger:好吧,然後爲了證明「那不是它」,請告訴我們你的代碼中的哪個部分實際上*會*初始化這個變量。 :P –

+0

我試着初始化它,但我不確定哪個構造函數初始化priorityComparator。 – nitiger