简体   繁体   English

在打印输出之前,应该将StringBuilder转换为String吗?

[英]Should StringBuilder be converted to String before printing out?

Does it make a difference if printing the contents of a StringBuilder object is done directly or if the .toString() method is called? 如果直接打印StringBuilder对象的内容或调用.toString()方法,是否会有所不同?

In particular 尤其是

StringBuilder sb = new StringBuilder("abc");
System.out.println(sb);
System.out.println(sb.toString());

Is one style preferred over the other? 是一种样式优先于另一种样式吗?

Can anyone comment on why the first way works? 任何人都可以评论为什么第一种方法有效吗? In Java does System.out.println implicitly call the .toString() method of an object? 在Java中, System.out.println隐式调用对象的.toString()方法?

As you guessed, PrintStream#println(Object) indeed automatically calls the toString() method of an object: 如您所料, PrintStream#println(Object)实际上会自动调用PrintStream#println(Object)toString()方法:

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

Where String.valueOf() is: 其中String.valueOf()为:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM