Java Reference
In-Depth Information
EXAMPLE: A Linked List with a Deep Copy clone Method
We have already discussed how and why the clone method of the generic linked
list class in Display 15.14 returns a deep copy. Let us now look at some of the other
details and see an example of using this linked list class.
Note the definition of the clone method. Why did we not simplify it to the
following?
public LinkedList<T> clone( )
{
return new LinkedList<T>( this );
}
This simple, alternative definition would still return a deep copy of the linked list and
would work fine in most situations. It is likely that you would not notice any difference
if you used this definition of clone in place of the one given in Display 15.14.
The only reason for all the other detail in the clone method definition given in
Display 15.14 is to define the clone method as specified in the Java documentation.
The reason that the Java documentation asks for those details has to do with security
issues. (Some might say that there are three ways to define a clone method: the right
way, the wrong way, and the Java way. This extra detail is the Java way.)
If you look only quickly at Display 15.14, you might think the following at the
start of the definition is an unimportant detail:
implements PubliclyCloneable
However, it ensures that the linked list class implements the Cloneable interface.
In order for a class to have a Java-approved clone method, it must implement the
Cloneable interface. It also allows you to make linked lists of linked lists and have a
deep copy clone method in the linked list of linked lists.
A sample class that implements the PubliclyCloneable interface is given in
Display 15.15 . Display 15.16 shows a demonstration program that makes a deep
copy clone of a linked list of objects of this sample class.
Display 15.15
A PubliclyCloneable Class (part 1 of 2)
1 public class StockItem implements PubliclyCloneable
2 {
3
private String name;
4
private int number;
5 public StockItem( )
6 {
7 name = null ;
8 number = 0;
9 }
 
Search WWH ::




Custom Search