When is StringBuffer/StringBuilder not implicitly used by the compiler?

半城伤御伤魂 提交于 2019-11-30 23:53:34

问题


I've heard that the compiler (or was it the JVM?) will automatically use a StringBuilder for some string concatenation. When is the right time to explicitly declare one? I don't need a StringBuffer for being thread-safe.

Thanks.


回答1:


The compiler will use it automatically for any string concatenation using "+".

You'd usually use it explicitly if you wanted to concatenate in a loop. For example:

StringBuilder builder = new StringBuilder();
for (String name : names)
{
    builder.append(name);
    builder.append(", ");
}
if (builder.length() > 0)
{
    builder.setLength(builder.length() - 2);
}
System.out.println("Names: " + builder);

Another situation would be where you wanted to build up a string over multiple methods, or possibly conditionalise some bits of the building. Basically, if you're not building the string in a single statement (where the compiler can help you) you should at least consider using StringBuilder.



来源:https://stackoverflow.com/questions/4262124/when-is-stringbuffer-stringbuilder-not-implicitly-used-by-the-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!