toString Override in Java

后端 未结 6 2001
悲哀的现实
悲哀的现实 2021-01-25 09:12

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

相关标签:
6条回答
  • 2021-01-25 09:50

    Use StringBuilder.

    StringBuilder builder = new StringBuilder();
    builder.append("some text");
    builder.append("more text");
    return builder.toString();
    
    0 讨论(0)
  • 2021-01-25 09:50

    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.

    0 讨论(0)
  • 2021-01-25 09:57

    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(", ");
    }
    }
    
    0 讨论(0)
  • 2021-01-25 10:00

    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.

    0 讨论(0)
  • 2021-01-25 10:03

    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.

    0 讨论(0)
  • 2021-01-25 10:03

    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();
    
    0 讨论(0)
提交回复
热议问题