Java Reference
In-Depth Information
Display 15.12
A Copy Constructor and
clone
Method for a Generic Linked List
(part 2 of 3)
18
private
Node<T> head;
<All the methods from Display 15.8 are in the class definition,
but they are not repeated in this display.>
19
/**
20
Produces a new linked list, but it is not a true deep copy.
21
Throws a NullPointerException if other is null.
22
*/
23
public
LinkedList3(LinkedList3<T> otherList)
24 {
25
if
(otherList ==
null
)
26
throw new
NullPointerException( );
27
if
(otherList.head ==
null
)
28 head = null;
29
else
30 head = copyOf(otherList.head);
31 }
32
33
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
*/