Java Reference
In-Depth Information
Display 15.11
An equals Method for the Linked List in Display 15.7 (part 2 of 2)
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
}
15.2
Copy Constructors and the clone Method
There are three ways to do anything:
The right way,
the wrong way,
and the army way.
Advice reputedly given to new army recruits
The way Java handles cloning, and object copying in general, is complicated and can
be both subtle and difficult. Some authorities think that the clone method was done
so poorly in Java that they prefer to ignore it completely and define their own methods
for copying objects. I have some sympathy for that view, but before you dismiss Java's
approach to cloning, it might be a good idea to see what the approach entails. Linked
data structures, such as linked lists, are an excellent setting for discussing cloning
because they are an excellent setting for discussing deep versus shallow copying.
This section first presents a relatively simple way to define copy constructors and
the clone method, but this approach unfortunately produces only shallow copies. We
then go on to present one way to produce a deep copy clone method and to do so
within the official prescribed rules of the Java documentation.
 
Search WWH ::




Custom Search