如何在用户定义的 class toString 方法中 return 填充数组项?

how to return filled array item in user defined class toString method?

该方法应该 return 数组中的所有填充项,但它 return 是数组中的最后一项。

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; 
   }

因为您总是用最新的

替换 result 字符串中的值
result =  String.format("%d. %s\n", i+1, list[i]);  // replaces the value always with latest 

所以使用 StringBuilder 附加所有值然后 return 它

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