toString Override in Java

烈酒焚心 提交于 2019-12-02 04:38:11

Use StringBuilder.

StringBuilder builder = new StringBuilder();
builder.append("some text");
builder.append("more text");
return builder.toString();

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.

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.

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.

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(", ");
}
}

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!