Java Reference
In-Depth Information
Display 15.12
A Copy Constructor and
clone
Method for a Generic Linked List
(part 2 of 2)
34
public
LinkedList3<T> clone( )
35
{
36
try
37
{
38
LinkedList3<T> copy =
39
(LinkedList3<T>)super.clone( );
40
if
(head ==
null
)
41
copy.head =
null
;
42
else
43
copy.head = copyOf(head);
44
return
copy;
45
}
46
catch
(CloneNotSupportedException e)
47
{//This should not happen.
48
return
null
;
//To keep the compiler happy.
49
}
50
}
51
/*
52
Precondition: otherHead != null
53
Returns a reference to the head of a copy of the list
54
headed by otherHead. Does not return a true deep copy.
55
*/
56
private
Node<T> copyOf(Node<T> otherHead)
57
{
58
Node<T> position = otherHead;
//moves down other's list.
59
Node<T> newHead;
//will point to head of the copy list.
60
Node<T> end =
null
;
//positioned at end of new growing list.
Invoking
clone
with
position.data
would be illegal.
61
//Create first node:
62
newHead =
63
new
Node<T>(position.data,
null
);
64
end = newHead;
65
position = position.link;
66
while
(position != null)
67
{
//copy node at position to end of new list.
68
end.link =
69
new
Node<T>(position.data, null);
70
end = end.link;
71
position = position.link;
72
}
Invoking
clone
with
position.data
would be illegal.
73
return
newHead;
74
}
75
}