This question is from an assignment. I have to override a toString() method in a class that creates a circularly linked list and I actually have a toString() method that works g
Use StringBuilder.
StringBuilder builder = new StringBuilder();
builder.append("some text");
builder.append("more text");
return builder.toString();
Strings
should always be used unless string builders offer an advantage in terms of simpler code or better performance
if you need to concatenate a large number of strings, appending to a StringBuilder
object
is more efficient.
Use StringBuilder
instead may do your a favor.This is snippet is copied from AbstractCollection.toString()
,take a look at it.
public String toString() {
Iterator<E> i = iterator();
if (! i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
I assume actualElement
is defined elsewhere in the class, though a better name might be nice. The if (output.equals(""))
is unnecessary. Just start the output StringBuilder
with a [, and just append to it.
However, you are depending on your list actually being circular. If this list ends up not looping around, you will get an NPE. And, if the list looks more like a 6, as in [A, B, C, D, E, C, D, E...], then the loop will never end.
To improve it further, you can use StringBuilder and append each computed String literals. This saves JVM creating load of individual String literals and thus improves performance.
First you should use a StringBuilder for concatenation of your Strings.
take a look here:
http://javarevisited.blogspot.co.at/2011/07/string-vs-stringbuffer-vs-stringbuilder.html
StringBuilder sb = new StringBuidler();
Node<E> tempNode = actualElement;
while (tempNode.next() != actualElement)
{
if (sb.length() == 0)
{
sb.append("[").append(tempNode.data().toString());
}
else
{
sb.append(", ").append(tempNode.data().toString());
}
tempNode = tempNode.next();
}
sb.append(", ").append(tempNode.data().toString()).append("]");
return sb.toString();