Java Reference
In-Depth Information
Display 15.12
A Copy Constructor and
clone
Method for a Generic Linked List
(part 3 of 3)
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 }
PITFALL: The
clone
Method Is Protected in
object
★
When defining the copy constructor and
clone
method for our generic linked list
(Display 15.12), we would have liked to have cloned the data in the list being copied.
We would have liked to change the code in the helping method
copyOf
by adding
invocations of the
clone
method as follows:
newHead =
new
Node((T)(position.data).clone( ),
null
);
end = newHead;
position = position.link;
while
(position !=
null
)
{
//copy node at position to end of new list.
end.link =
new
Node((T)(position.data).clone( ),
null
);
end = end.link;
position = position.link;
}
This code is identical to code in
copyOf
except for the addition of the invocations of
clone
and the type casts. (The type casts are needed because Java thinks
clone
returns
a value of type
Object
.)
(continued)