Search code examples
javalistgenericslinked-listsentinel

What is wrong with this contains(T entry) method? Java. Linked List


I'm making a linked list class and am trying to implement this contains() method.

I have head and tail sentinel nodes, so I have the loop start at head.next. length is the size of the list. Bout all I can give you guys :O

public boolean contains(T entry) {

    boolean found = false;
    Node current = head.next;

    for (int i = 0; i < length; i++) {

        if (current.equals(entry)) {

            found = true;
        }
        current = current.next;
    }
    return found;
}

Solution

  • The problem is you're comparing a Node to a T which if your equals method correctly fufills the correct contract will always return false being different classes.

    i.e. re-examine this line:

    if (current.equals(entry)) {