我正在构建一个基于控制台的清单程序,并且想重写toString()方法以将客户对象打印到屏幕上。

我对方法有以下了解,但它们看起来都很混乱。哪个是更好的做法?

String toString = (name + newLine +
                       addressLine_1 + newLine +
                       addressLine_2 + newLine +
                       city + newLine +
                       country + newLine +
                       postCode + newLine);


String toString = System.out.println(String.format("%s%n%s%n%s**%n%s%n%s%n%s%n", name, addressLine_1, addressLine_2, city, country, postCode));

最佳答案

使用字符串生成器!

StringBuilder strBuilder = new StringBuilder();
strBuilder.append( name );
strBuilder.append( System.getProperty( "line.separator" ) );
strBuilder.append( addressLine_1 );
/* ... */

System.out.println( strBuilder.toString() );
return strBuilder.toString();


使用StringBuilder(或对于JDK的较早版本为StringBuffer)不仅更具可读性,而且还使字符串连接更加有效。另外,使用System.getProperty( "line.separator" )确保跨平台的行尾。

10-06 11:04
查看更多