【发布时间】:2012-12-30 04:54:12
【问题描述】:
据我所知,当您有大量字符串时,使用 + 号连接字符串不是一个好习惯。但是当我检查 eclipse 生成的 toString() 方法时(点击源文件 -> 源 -> 生成 toString() )它具有相同的。
public class Temp
{
private String tempName;
private String tempValue;
// here getters and setters
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Temp [tempName=" + tempName + ", tempValue=" + tempValue + "]";
}
}
是否有任何地方可以像我预期的 toString() 方法一样在 Eclipse 中进行配置,或者为什么 Eclipse 不考虑这一点。
public String expectedToString(){
StringBuffer sb = new StringBuffer();
sb.append("Temp [tempName=").append(tempName).append(",").append(" tempValue=").append(tempValue).append("]");
return sb.toString();
}
我将使用自动生成的 toString() 方法来记录我的对象值。
请给我建议。
【问题讨论】:
-
IIRC 1) 现在最好的方法是使用
StringBuilder和 2) 现在编译器将String +更改为StringBuilder表达式。有人可以确认吗? -
使用 + 连接不再是问题。编译器优化了 + 的使用,尤其是在涉及多个字符串时。
-
非问题:"+" 和 ".append()" 和 ".concat()" 在这种情况下应该执行相同的操作。有趣的链接:vogella.com/blog/2009/07/19/java-string-performanc 和 Yet again on string append vs concat vs +