Java Reference
In-Depth Information
The copy constructor is defined by using the private helping method
copyOf
to
create a copy of the list of nodes. Other details of the copy constructor and the
clone
method are done in the standard way.
Although the copy constructor and the
clone
method each produce a new linked
list with all new nodes, the new list is not truly independent because the data objects
are not cloned. See the Pitfall “The
clone
Method Is Protected in
Object
★
” for
a discussion of this point. One way to fix this shortcoming is discussed later in the
Programming Tip entitled “Use a Type Parameter Bound for a Better
clone
.”
Exceptions
★
A generic data structure, such as the class
LinkedList
in Display 15.12 , is likely
to have methods that throw exceptions. Situations such as a
null
argument to
the copy constructor might be handled differently in different situations, so it is
best to throw a
NullPointerException
if this happens and let the programmer
who is using the linked list handle the exception. This is what we did with the
copy constructor in Display 15.12 . A
NullPointerException
is an unchecked
exception, which means that it need not be caught or declared in a
throws
clause.
When thrown by a method of a linked list class, it can be treated simply as a run-
time error message. The exception can instead be caught in a
catch
block if there is
some suitable action that can be taken.
Display 15.12
A Copy Constructor and
clone
Method for a Generic Linked List
(part 1 of 3)
1
public class
LinkedList3<T>
implements
Cloneable
2 {
3
private
class Node<T>
4 {
5
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 “Use a Type Parameter
Bound for a Better
clone
.“
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
(continued)