Java Reference
In-Depth Information
2. Two linked lists are equal if they contain the same data entries in the same order;
that is, the data in the fi rst node of the calling object equals the data in the fi rst 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 trust
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 such as this are the reason it is so important to always include an
equals
method in the classes you define.
Display 15.11
An
equals
Method for the Linked List in Display 15.7
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
;
11
else
12 {
13 LinkedList2 otherList = (LinkedList2)otherObject;
14
if
(size( ) != otherList.size( ))
15
return false
;
16 Node position = head;
17 Node otherPosition = otherList.head;
18
while
(position !=
null
)
19 {
20
if
( (!(position.item.equals(otherPosition.item))))
21
return false
;
22 position = position.link;
23 otherPosition = otherPosition.link;
24 }
25
return true
;
//A mismatch was not found
26 }
27 }