2012-10-22 56 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