Robert
Robert

Reputation: 143

NPE when searching element in the LinkedList

i'm searching an element in the LinkedList, output is correct when the element is indeed in the list. However, testing the opposite case, when searching for Null or element not in the list, NPE happens. Please help, thanks!

public boolean find(E e){
    Node current=head;
    while(current.item !=null){
        if(e.equals(current.item)){
            System.out.println("True");
            return true;
        }
        current=current.next;
    }
    System.out.println("False");
    return false;
}

Upvotes: 0

Views: 55

Answers (2)

akhil_mittal
akhil_mittal

Reputation: 24167

May be you need to change the condition in while loop:

public boolean find(E e){
    Node current=head;
    while(current != null){
        if( (current.item != null) && (e.equals(current.item)){
            System.out.println("True");
            return true;
        }
        current=current.next;
    }
    System.out.println("False");
    return false;
}

Also check if item in the node is not null.

Upvotes: 1

locoyou
locoyou

Reputation: 1697

The while statement should be while(current !=null)

Upvotes: 2

Related Questions