Java Reference
In-Depth Information
Display 15.14
A Generic Linked List with a Deep Copy clone Method (part 3 of 3)
< The rest of the definition is the same as in Display 15.8. The only difference
between this definition of equals and the one in Display 15.8 is that we
have replaced the class name LinkedList3<T> with LinkedList<T> . >
89
}
< All the other methods from Display 15.8 are in the class definition,
but are not repeated in this display. >
90
public String toString( )
91
{
92
Node<T> position = head;
93
String theString = "";
94
while (position != null )
95
{
96
theString = theString + position.data + "\n";
97
position = position.link;
98
}
99
return theString;
We added a toString method so LinkedList<T>
would have all the properties we want T to have.
100
}
101
}
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's 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 differ-
ence 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 Dis-
play 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.)
 
Search WWH ::




Custom Search