Java Reference
In-Depth Information
This is the simplest change that fixes the program, but it is not the best. The original program used
an inner class unnecessarily. As mentioned in Puzzle 80 , you should prefer static member classes
over nonstatic [EJ Item 18]. An instance of LinkedList.Node contains not only the value and
next fields but also a hidden field containing a reference to the enclosing LinkedList instance.
Although the enclosing instance is used during construction to read and then modify head , it is dead
weight once construction has completed. Worse, placing the side effect of changing head into the
constructor makes the program confusing to the reader. Change instance fields of a class only in
its own instance methods.
A better fix, then, is to modify the original program to move the manipulation of head into
LinkedList.add , making Node a static nested class rather than a true inner class. Static nested
classes do not have access to the type parameters of enclosing classes, so now Node really does need
a type parameter of its own. The resulting program is simple, clear, and correct:
class LinkedList<E> {
private Node<E> head = null;
private static class Node<T> {
T value; Node<T> next;
Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
}
public void add(E e) {
head = new Node<E>(e, head);
}
public void dump() {
 
 
Search WWH ::




Custom Search