Java Reference
In-Depth Information
has access to the public post office. But in a corporate office setting, mailboxes often
are not locked because only a limited number of people have access to them and,
therefore, people are willing to be more informal.
Later in the chapter we will see an even better way of handling this case by includ-
ing the node class as a static inner class. But for now we'll work with the two classes
to keep things simple.
As a first exercise, let's add a method to our class that will allow us to examine the
contents of the list. We saw that code like the following could be used to print a list:
ListNode current = list;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
We could turn that into a method of the class by initializing the local variable to
the value of our field front :
public void print() {
ListNode current = front;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
But as we saw in Chapter 15, it is a better idea to make this a toString method
that returns a String representation of the list. For the ArrayIntList class we
wrote the following method:
public String toString() {
if (size == 0) {
return "[]";
} else {
String result = "[" + elementData[0];
for (int i = 1; i < size; i++) {
result += ", " + elementData[i];
}
result += "]";
return result;
}
}
The code is very similar for the LinkedIntList class because we will have the
same special case for an empty list and the same fencepost loop to make sure that
Search WWH ::




Custom Search