编译器何时不隐式使用StringBuffer / StringBuilder? [英] When is StringBuffer/StringBuilder not implicitly used by the compiler?

查看:68
本文介绍了编译器何时不隐式使用StringBuffer / StringBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说编译器(或者是JVM?)将自动使用StringBuilder进行某些字符串连接。何时才是合适的时间明确声明一个?我不需要StringBuffer来保证线程安全。

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.

谢谢。

推荐答案

编译器将使用 +将其自动用于任何字符串连接。

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);

另一种情况是您想在多个方法上构建字符串,或者可能有条件地对一些位进行条件化建筑的。基本上,如果您不是在单个语句(编译器可以帮助您)中构建字符串,则至少应考虑使用 StringBuilder

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.

这篇关于编译器何时不隐式使用StringBuffer / StringBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆