简体   繁体   中英

Null Pointer Exception implementing a find method for a doubly linked list in Java

I'm trying to implement a find method for a doubly linked list. When I run tests, i keep getting a null pointer exception on my find method.

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

The part of the test where I get a null pointer exception is here

        list.remove(m4);
    if (list.find(m4) != -1) {                  //error occurs on this line
        System.out.println("FAILURE");
        return;

I'm not really sure how to go about fixing this as my find method seems to be working otherwise

If your linkedList implementation is done by allowing your items to be null , then nullPointers can happen in your find() . Simply replace this

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

with this

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

There is no check in your find method to determine if there are any elements in your list. So, you need to first check that head or curr is not null before entering the for loop. Or, you are not properly tracking your count as Jimmy pointed out.

A better solution would be to not depend on count and check that curr.next is not null. Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM