Java Reference
In-Depth Information
Display 15.14
A Generic Linked List with a Deep Copy clone Method (part 2 of 3)
13 public Node(T newData, Node<T> linkValue)
14 {
15 data = newData;
16 link = linkValue;
17 }
18 } //End of Node<T> inner class
19
private Node<T> head;
20 public LinkedList( )
21 {
22 head = null ;
23 }
24 / **
25 Produces a new linked list, but it is not a true deep copy.
26 Throws a NullPointerException if other is null.
27 * /
28 public LinkedList(LinkedList<T> otherList)
29 {
30 if (otherList == null )
31 throw new NullPointerException( );
32 if (otherList.head == null )
33 head = null ;
34 else
35 head = copyOf(otherList.head);
36 }
37
38 public LinkedList<T> clone( )
39 {
40 try
41 {
42 LinkedList<T> copy =
43 (LinkedList<T>)super.clone( );
44 if (head == null )
45 copy.head = null ;
46 else
47 copy.head = copyOf(head);
48
return copy;
49 }
50 catch (CloneNotSupportedException e)
51 { //This should not happen.
52
return null ; //To keep the compiler happy.
53 }
54 }
55 / *
56 Precondition: otherHead != null
57 Returns a reference to the head of a copy of the list
58 headed by otherHead. Returns a true deep copy.
59
* /
60
private Node<T> copyOf(Node<T> otherHead)
Search WWH ::




Custom Search