无法摆脱Comparator的NullPointerException

时间:2012-10-22 02:41:01

标签: java 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 个答案:

答案 0 :(得分:5)

好像你没有初始化你的PriorityComparator。

private Comparator<? super E> priorityComparator;

应该是

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