我一直在努力擺脫調用的代碼行時出現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;
我沒有看到任何錯誤的參數,所以我真的難倒了。我怎樣才能解決這個問題?
檢查temp.next.value,newNode.value爲空或不 –
我會承擔,要麼priorityComparator爲空或temp.next.value爲空或newNode .value爲null。在調試器中查看變量。實際的錯誤信息說什麼? –
打印或調試程序以找出錯誤。任何人:priorityComparator,temp,temp.next或newNode。根據實施情況,也可以是temp.next.value或newNow.value。 – John3136