Java Reference
In-Depth Information
Display 15.14
A Generic Linked List with a Deep Copy
clone
Method
(part 2 of 3)
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
}
This definition of
copyOf
gives
a deep copy of the linked list.
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)
61
{
62
Node<T> position = otherHead;
//moves down other's list.
63
Node<T> newHead;
//will point to head of the copy list.
64
Node<T> end =
null
;
//positioned at end of new growing list.
65
//Create first node:
66
newHead =
67
new
Node<T>((T)(position.data).clone( ),
null
);
68
end = newHead;
69
position = position.link;
70
while
(position !=
null
)
71
{
//copy node at position to end of new list.
72
end.link =
73
new
Node<T>((T)(position.data).clone( ),
null
);
74
end = end.link;
75
position = position.link;
76
}
77
return
newHead;
78
}
79
80
public
boolean
equals(Object otherObject)
81
{
82
if
(otherObject ==
null
)
83
return
false
;
84
else
if
(getClass( ) != otherObject.getClass( ))
85
return
false
;
86
else
87
{
88
LinkedList<T> otherList = (LinkedList<T>)otherObject;
(continued)