【发布时间】:2013-04-04 14:28:59
【问题描述】:
这个问题来自一个作业。我必须在创建循环链接列表的类中重写 toString() 方法,实际上我有一个很好用的 toString() 方法,它通过了我所有的测试。所以我的项目是自动评分的,它显然没有 100% 批准我的方法。所以我的问题是:有没有更好的方法来编写这个 toString() 方法,效率更高?
public String toString()
{
if (size == 0)
{
return "[]";
}
else
{
String output = "";
Node<E> tempNode = actualElement;
while (tempNode.next() != actualElement)
{
if (output.equals(""))
{
output = "[" + output + tempNode.data().toString();
tempNode = tempNode.next();
}
else
{
output = output + ", " + tempNode.data().toString();
tempNode = tempNode.next();
}
}
output = output + ", " + tempNode.data().toString() + "]";
return output;
}
如果我需要详细说明类结构以便更有意义,请告诉我。
【问题讨论】:
-
您应该使用
StringBuilder进行有效连接。 -
你说它是自动分级的。你知道确切的评分标准吗?
-
在循环中与
+的字符串连接不是最佳的,这可能就是您对自动评分感到厌烦的原因。按照其他人的建议使用StringBuilder。 -
@CedricReichenbach 我不知道评分标准是什么......我尝试了几种不同的方法来构建字符串,但这是我迄今为止的“最佳”。
-
好的,感谢您的提示,似乎每个人都在将我指向 StringBuilder,所以我会调查一下,看看我得到了什么结果。
标签: java performance tostring