Question

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;
}
Was it helpful?

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)) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top