Java Reference
In-Depth Information
Display 15.12
A Copy Constructor and
clone
Method for a Generic Linked List
(part 1 of 2)
1
public
class
LinkedList3<T>
implements
Cloneable
2{
3
private
class Node<T>
4
{
This copy constructor and this
clone
method
do not make deep copies. We discuss one way
to make a deep copy in the Programming Tip
subsection “Use a Type Parameter Bound for a
Better
clone
.”
5
private
T data;
6
private
Node<T> link;
7
public
Node( )
8
{
9
data =
null
;
10
link =
null
;
11
}
12
public
Node(T newData, Node<T> linkValue)
13
{
14
data = newData;
15
link = linkValue;
16
}
17
}
//End of Node<T> inner class
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