在 Java 中为双向链表实现查找方法的空指针异常



>我正在尝试为双向链表实现一个查找方法。 当我运行测试时,我的 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;

我不太确定如何解决这个问题,因为我的查找方法似乎在其他情况下有效

如果你的linkedList实现是通过允许你的项目被null来完成的,那么nullPointers可以发生在你的find()中。只需替换此

if (curr.item.equals(item)){ 

有了这个

if (curr.item != null && curr.item.equals(item)){ 

查找方法中没有检查来确定列表中是否有任何元素。因此,在进入 for 循环之前,您需要首先检查 head 或 curr 是否为空。或者,你没有像吉米指出的那样正确跟踪你的计数。

更好的解决方案是不依赖于计数并检查curr.next是否为空。像这样:

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;
}

最新更新