Finally we provide a method for converting lists to strings. This will return a string of the form
[4, 2, 6, 8, 9]for example. If the list is empty it will return
[]The code is shown in Figure 6.10
public String toString() {
String string = "";
string += "[";
if (head != null) {
string += head.data;
ListNode current = head.next;
while (current != null) {
string += ", " + current.data;
current = current.next;
}
}
string += "]";
return string;
}
|
+= as a simple way of appending a string to the end of a given string.
This will automatically invoke the toString method of the
data items. Possibly for lists of complex data, some other method of
pretty printing might be preferable. But this could be achieved by
simply enumerating the elements of the list, using the
elements method, and then printing them in whatever form is
most suitable.