Java Reference
In-Depth Information
But if we need a list of characters, we would need to change the heading to this:
public void addHead(char c)
and, for a list of
Part
objects, to this:
public void addHead(Part p)
If there are many methods in the class, these changes could become quite tedious every time we need to change
the kind of data stored in our list.
We will use an approach that will minimize the changes required in
LinkedList
.
Let's define the class
Node
as follows:
class Node {
NodeData data;
Node next;
public Node(NodeData nd) {
data = nd;
next = null;
}
} //end class Node
We write the class in terms of an unspecified, as yet, data type,
NodeData
. There are two fields,
data
and
next
.
Without knowing anything more about
NodeData
, we can write
addHead
as follows:
public void addHead(NodeData nd) {
Node p = new Node(nd);
p.next = head;
head = p;
}
A class (
TestList
, say) that wants to use
LinkedList
must provide a definition of
NodeData
that is available to
LinkedList
. Suppose we want a linked list of integers. We can define
NodeData
as follows (we will explain the need for
toString
shortly):
public class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public String toString() {
return num + " ";
//" " needed to convert num to a string; may also use "" (empty string)
}
} //end class NodeData
Search WWH ::
Custom Search