next up previous index
Next: The toString method Up: Linked Lists Previous: The header node.   Index


Equality

We now implement the equality method for lists. Recall that each Java object inherits the basic equals method of the Object class defined by

public boolean equals(Object obj) {
    return (this == obj);
}
This is a very strict equality. For any reference values x and y, this method returns true if and only if x and y refer to the same object. This means that the relation is more one of identity than equality.

A more useful idea of equality for lists is that the two lists are equal if the have the same elements, and in the same order. This is shown in Figure 6.9.

Figure 6.9: The equality method for linked lists.
public boolean equals(Object other) {
    if (other == null ||
        !(other instanceof LinkedList) ||
        this.size != ((LinkedList) other).size) {
        return false;
    }
    ListNode p = this.head;
    ListNode q = ((LinkedList) other).head;
    while (p != null) { 
        if (!p.data.equals(q.data)) {
            return false;
        }
        p = p.next;
        q = q.next;
    }
    return true;
}

The parameter of the method is an Object rather than a LinkedList. This is because we want to override the Object method, so we must use the same form. In any case we want to be able to say of our linked list whether or not it is equal to anything else, not just a linked list.

We first check whether the other object is null. If it is, our linked list cannot be equal to it. (Remember that an empty list has head equal to null, but the list, as an object, is not null). Provided other is not null, we can ask whether other is an instance of a LinkedList. We are relying here on lazy evaluation of disjunction. Assuming that other is indeed a LinkedList, we can ask whether it has the same size as our list. This is a simple and efficient check to perform at this stage. If the other list is of a different size, it cannot be equal to our list. Note that we have to remind the interpreter or compiler that other is a LinkedList by referring to ((LinkedList) other).size. If all these tests have been passed, we know that other is a linked list of the same size as ours. So now we only have to run through the elements of the two lists checking whether they are the same. To do that, we invoke the equals method of the data items in our list. As soon as we find a failure of equality we can return false. If we exit the while loop without returning, we have reached the end of our list--which we know is also the end of the other list since they have the same size--and then and only then can we finally return true.


next up previous index
Next: The toString method Up: Linked Lists Previous: The header node.   Index
Peter Williams 2005-06-07