[英]Should StringBuilder be converted to String before printing out?
如果直接打印StringBuilder对象的内容或调用.toString()
方法,是否会有所不同?
尤其是
StringBuilder sb = new StringBuilder("abc");
System.out.println(sb);
System.out.println(sb.toString());
是一种样式优先于另一种样式吗?
任何人都可以评论为什么第一种方法有效吗? 在Java中, System.out.println
隐式调用对象的.toString()
方法?
如您所料, PrintStream#println(Object)
实际上会自动调用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.