【问题标题】:how to return filled array item in user defined class toString method?如何在用户定义的类 toString 方法中返回填充的数组项?
【发布时间】:2020-04-03 23:30:06
【问题描述】:
该方法应该从数组中返回所有已填充的项,但它会返回数组中的最后一项。
public String toString() {
String result = "";
for( int i = 0; i < list.length; i++ )
{
result = String.format("%d. %s\n", i+1, list[i]);
}
return result;
}
【问题讨论】:
标签:
java
arrays
class
tostring
【解决方案1】:
因为你总是用最新的替换result 字符串中的值
result = String.format("%d. %s\n", i+1, list[i]); // replaces the value always with latest
所以使用 StringBuilder 附加所有值然后返回它
public String toString() {
StringBuilder builder = new StringBuilder();
for( int i = 0; i < list.length; i++ )
{
builder.append(String.format("%d. %s\n", i+1, list[i]));
}
return builder.toString();
}