toString Override in Java

后端 未结 6 2002
悲哀的现实
悲哀的现实 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 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 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();
    

提交回复
热议问题