直接打印 StringBuilder 对象的内容或调用 .toString()
方法有区别吗?
特别是
StringBuilder sb = new StringBuilder("abc");
System.out.println(sb);
System.out.println(sb.toString());
是否更喜欢其中一种风格?
任何人都可以评论为什么第一种方法有效吗?在 Java 中,System.out.println
是否隐式调用对象的 .toString()
方法?
最佳答案
正如您所猜测的,PrintStream#println(Object)
确实会自动调用对象的 toString()
方法:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
其中String.valueOf()
是:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
关于java - StringBuilder 应该在打印之前转换为 String 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770812/