Java Reference
In-Depth Information
PITFALL:
(continued)
Sometimes a compiler warning message can be helpful when you make this mis-
take. If you get a warning that mentions a type cast from
Node
to
Node<T>,
look for an
omitted
<T>
.
Finally, we should note that sometimes your code will compile and even run cor-
rectly if you omit the
<T>
from
Node<T>
.
■
The
equals
Method for Linked Lists
The linked lists we presented in Displays 15.3 and 15.7 did not have an
equals
method. We did that to keep the examples simple and not detract from the main mes-
sage. However, a linked list class should normally have an
equals
method.
There is more than one approach to defining a reasonable
equals
method for a
linked list. The two most obvious are the following:
1. Two linked lists are equal if they contain the same data entries (possibly ordered
differently).
2. Two linked lists are equal if they contain the same data entries in the same order; that is,
the data in the first node of the calling object equals the data in the first node of the
other linked list, the data in the two second nodes are equal, and so forth.
It is not true that one of these is the correct approach to defining an
equals
method
and the other is incorrect. In different situations, you might want different definitions
of
equals
. However, the most common way to define
equals
for a linked list is
approach 2. A definition of
equals
that follows approach 2 and that can be added to
the class
LinkedList2
in Display 15.7 is given in Display 15.11. The generic linked
list in Display 15.8 also contains an
equals
method that follows approach 2.
Note that when we define
equals
for our linked list with type parameter
T
, we are
trusting the programmer who wrote the definition for the type plugged in for
T
. We
are assuming the programmer has redefined the
equals
method so that it provides a
reasonable test for equality. Situations like this are the reason it is so important to
always include an
equals
method in the classes you define.
equals
Display 15.11
An
equals
Method for the Linked List in Display 15.7
(part 1 of 2)
1
/*
2
For two lists to be equal they must contain the same data items in
3
the same order.
4
*/
5
public
boolean
equals(Object otherObject)
6
{
7
if
(otherObject ==
null
)
8
return
false
;
9
else
if
(getClass( ) != otherObject.getClass( ))
10
return
false
;
(continued)