[英]Null Pointer Exception implementing a find method for a doubly linked list in Java
我正在嘗試為雙向鏈表實現find方法。 在運行測試時,我的find方法不斷收到空指針異常。
public int find(Medication item) {
MedicationNode curr = head;
for (int k = 0; k < count; k++) {
if (curr.item.equals(item)){ //error occurs on this line
return k;
}
curr = curr.next;
}
return -1;
}
我得到空指針異常的測試部分在這里
list.remove(m4);
if (list.find(m4) != -1) { //error occurs on this line
System.out.println("FAILURE");
return;
我不確定如何解決此問題,因為我的find方法似乎可以正常工作
如果您通過允許您的項目為null
來完成linkedList實現,則nullPointers可以在find()
發生。 只需替換此
if (curr.item.equals(item)){
有了這個
if (curr.item != null && curr.item.equals(item)){
您的find方法中沒有檢查以確定列表中是否有任何元素。 因此,在進入for循環之前,您需要首先檢查head或curr不為null。 或者,如吉米指出的那樣,您沒有正確跟蹤計數。
更好的解決方案是不依賴於計數並檢查curr.next不為null。 就像是:
public int find(Medication item) {
MedicationNode curr = head;
while(curr != null){
if (curr.item != null && curr.item.equals(item)){
return k;
}
curr = curr.next;
}
return -1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.