Java Reference
In-Depth Information
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.
Readers with very little programming experience may be better off skipping this
entire section until they become more comfortable with Java. Other readers may
prefer to read only the first subsection and possibly the Pitfall “The clone Method Is
Protected in Object
Simple Copy Constructors and clone Methods
Display 15.12 contains a copy constructor and clone method definitions that could
be added to the definition of the generic linked list class in Display 15.8. The real
work is done by the private helping method copyOf , so our discussion focuses on the
method copyOf .
The private method copyOf takes an argument that is a reference to the head node
of a linked list and returns a reference to the head node of a copy of that linked list. The
easiest way to do this is to return the argument. This would, however, simply produce
another name for the argument list. We do not want another name; we want another
list. So, the method goes down the argument list one node at a time (with position )
and makes a copy of each node. The linked list of the calling object is built up node by
node by adding these new nodes to its linked list. However, there is a complication. We
cannot simply add the new nodes at the head (start) end of the list being built. If we
did, then the nodes would end up in the reverse of the desired order. So, the new nodes
are added to the end of the linked list being built. The variable end of type Node<T>
is kept positioned at the last node so that it is possible to add nodes at the end of the
linked list being built. In this way, a copy of the list in the calling object is created so
that the order of the nodes is preserved.
 
 
Search WWH ::




Custom Search