views:

61

answers:

5

Is there any way to abbreviate the print() and toString() into one function in a Java linked list function or is there any explanation as to why someone would format this way?

public void print() {
    System.out.println(this.toString());
}

@Override
public String toString() {
    String display = "";
    LinkedList current = this;
    while (current != null) {
        display += new Integer(current.head).toString() + ",";
        current = current.tail;
    }
    display = display.substring(0, display.length()-1);
    return display;
}
A: 

No. There is no way to do that in Java 6. Future Javas? Don't know. :-)

The way you are doing it, it's pretty much the more concise way to achieve it.

Pablo Santa Cruz
+1  A: 

I would use StringBuilder, because it's more memery efficient :

public void print() {
    System.out.println(this.toString());
}

@Override
public String toString() {
    StringBuilder display = new StringBuilder();
    for(Integer current: this) {
        display.append(current).append(',');
    }
    return display.toString().substring(0, display.length()-1);
}
Jean-Philippe Caruana
A: 

The reason it's done like this is that if you want to write a number of child classes which report themselves as Strings in different ways, you only have to override the toString() function on each, not the toString() and the print() function. If you want print() and toString() to have different functionality there is no reason why you can't override just print() to make it not call toString().

DJClayworth
A: 

The code you've shown is very amateurishly written. Concatenating into a String is just the main red flag.

If you're not too concerned about performance, you could stringify the whole list in one line of code:

return Arrays.deepToString(toArray());

Of course this depends on elements of the list having sensible toString() methods of their own.

Carl Smotricz
A: 

You could add a toString() to the class representing a node of your linked list:

class Node<T> {
    T value;
    Node<T> next;

    public String toString() {
        return value + (next != null ? ", " + next : "");
    }
}

And then implement the toString() of your linked list as follows:

public class LinkedList<T> {
    Node<T> head;

    public String toString() { 
        return "[" + (head != null ? head : "") + "]";
    }
}

This way it will print the nodes recursively.

The print() function in turn can be replaced by just printing this since System.out.println(object) under the hoods returns String.valueOf(object) which in turn under the hoods returns object != null ? object.toString() : "null".

public void print() {
    System.out.println(this);
}
BalusC