0

我一直在努力摆脱调用代码行时发生的 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;

我看不出参数有什么问题,所以我真的很难过。我怎样才能解决这个问题?

4

1 回答 1

5

似乎您没有初始化 PriorityComparator。

private Comparator<? super E> priorityComparator;

应该是这样的

private Comparator<? super E> priorityComparator = new PriorityComparator();
于 2012-10-22T02:48:25.513 回答