Java Reference
In-Depth Information
try
{
theCopy = (LList<T>) super .clone();
}
catch (CloneNotSupportedException e)
{
throw new Error(e.toString());
}
// copy underlying chain of nodes
if (firstNode == null ) // if chain is empty
{
theCopy.firstNode = null ;
}
else
{
// make a copy of the first node
theCopy.firstNode = (Node)firstNode.clone();
// make a copy of the rest of chain
Node newRef = theCopy.firstNode;
Node oldRef = firstNode.getNextNode();
for ( int count = 2; count <= numberOfEntries; count++)
{
// clone node and its data; link clone to new chain
newRef.setNextNode((Node)oldRef.clone());
newRef = newRef.getNextNode();
oldRef = oldRef.getNextNode();
} // end for
} // end if
return theCopy;
} // end clone
Note: To make a deep clone of a chain of linked nodes that reference cloneable objects,
you must clone the nodes as well as the objects.
Question 5 The for statement in Segment 30.27 is controlled by the number of nodes in
the chain. Revise this statement and its associated body so that it is controlled by oldRef .
A Sorted List of Clones
30.28
Segment 30.4 talked about the danger of placing mutable objects in a collection such as a sorted list. If
the client retains a reference to any of the objects, it could alter those objects and destroy the integrity
of the collection. In the case of a sorted list, the client could destroy the sorted order of the objects.
Segment 30.5 offered one solution to this problem, namely to place only immutable objects
in the collection. This section offers another solution that enables you to place mutable objects in
the collection.
Suppose that a client adds an object to a collection. Imagine that the collection clones the
object before adding it to its data. The client then would be able to access or change the collection's
data only by using ADT operations. It would not have a reference to the clone that it could use to
alter the clone. Of course, this scenario requires that the added object be Cloneable . Let's examine
the details of such an implementation of the ADT sorted list.
 
Search WWH ::




Custom Search