Java Reference
In-Depth Information
protected
Object clone()
{
Node theCopy =
null
;
try
{
theCopy = (Node)
super
.clone();
}
catch
(CloneNotSupportedException e)
{
throw new
Error(e.toString());
}
theCopy.data = (T)data.clone();
theCopy.next =
null
;
// don't clone link; it's set later
return
theCopy;
}
// end clone
}
// end Node
Remember that
data
invokes a public method
clone
that does not throw an exception, and so
data.clone()
can appear outside of a
try
block.
30.26
Cloning the chain.
LList
's
clone
method invokes
super.clone()
in a statement such as
LList<T> theCopy = (LList<T>)
super
.clone();
The method then must clone the chain of nodes that stores the list's data. To do so, the method
needs to traverse the chain, clone each node, and link the cloned nodes appropriately. We begin by
cloning the first node so that we can set the data field
firstNode
correctly:
// make a copy of the first node
theCopy.firstNode = (Node)firstNode.clone();
Next, we traverse the rest of the chain. A reference
newRef
references the last node that we
have added to the new chain, while the reference
oldRef
keeps track of where we are in the tra-
versal of the original chain. The statement
newRef.setNextNode((Node)oldRef.clone());
// attach cloned node
clones the current node in the original chain, along with its data, and then links the clone to the end
of the new chain. Recall that
Node
's
clone
method also clones the data that a node references.
The following statements incorporate the previous ideas and clone the rest of the chain:
Node newRef = theCopy.firstNode;
// last node in new chain
Node oldRef = firstNode.getNextNode();
// next node in old chain
for
(
int
count = 2; count <= numberOfEntries; count++)
{
newRef.setNextNode((Node)oldRef.clone());
// attach cloned node
newRef = newRef.getNextNode();
// update references
oldRef = oldRef.getNextNode();
}
// end for
30.27
The code in the previous segment assumes a nonempty chain of nodes. The complete
clone
method
that follows checks for an empty chain.
public
Object clone()
{
LList<T> theCopy =
null
;