next up previous index
Next: Code and demonstration Up: Linked Lists Previous: Equality   Index

The toString method

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

Figure 6.10: A toString method for linked lists.
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;
}

where we use += 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.



Peter Williams 2005-06-07