Sunday, 2 June 2013

Recursive toString Method

Recursive toString Method

I'm working on my current assignment which is to create a LinkedList data structure, and I've created it as well as the other methods, and it works perfectly fine. I'm on my last question which is to make a toString method. Which is supposed to:
"toString method to return a String representation of the list. Separate each item with a comma, and enclose the items in braces, e.g. {1,4,7,5}. The public toString method must call a private, recursive method to generate the comma separated list of items. (You may add the braces in the public method though.)"
I have my public toString method working;
    public String toString() {
    int size = getSize();
    String str = "{ ";
    Link current = first;

    for(int i = 0; i < getSize(); i++, current = current.next) {
        str += current.getiData() + " ";
    }

    str += " }";
    return str;
}
(I know I should be using StringBuilder, just using += temporarily.) However for the private method I'm confused as to even write it. Right now the only way I can think of doing this would be as:
private String toString(int x) {
    if(i > 0) {
        toString(--x);
    }
    return ", ";
}
Which is just stupid (and really isn't recursion), can anyone clarify what is meant to be done, and/or give pseudo code?

No comments:

Post a Comment