为什么StringBuilder有String? [英] Why StringBuilder when there is String?
问题描述
我第一次遇到 StringBuilder
,并且因为Java已经有一个非常强大的 String
类而感到惊讶允许追加。
I just encountered StringBuilder
for the first time and was surprised since Java already has a very powerful String
class that allows appending.
为什么第二个字符串
类?
我在哪里可以了解更多关于 StringBuilder
?
Where can I learn more about StringBuilder
?
推荐答案
字符串
不允许附加。您在 String
上调用的每个方法都会创建一个新对象并将其返回。这是因为 String
是不可变的 - 它不能改变其内部状态。
String
does not allow appending. Each method you invoke on a String
creates a new object and returns it. This is because String
is immutable - it cannot change its internal state.
另一方面 StringBuilder
是可变的。当你调用 append(..)
时,它会改变内部char数组,而不是创建一个新的字符串对象。
On the other hand StringBuilder
is mutable. When you call append(..)
it alters the internal char array, rather than creating a new string object.
因此更有效:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 500; i ++) {
sb.append(i);
}
而不是 str + = i
,这将创建500个新的字符串对象。
rather than str += i
, which would create 500 new string objects.
请注意,在示例中我使用循环。正如helios在评论中指出的那样,编译器会自动将 String d = a + b + c
等表达式转换为
Note that in the example I use a loop. As helios notes in the comments, the compiler automatically translates expressions like String d = a + b + c
to something like
String d = new StringBuilder(a).append(b).append(c).toString();
另请注意另外还有 StringBuffer
到 StringBuilder
。不同之处在于前者具有同步方法。如果将其用作局部变量,请使用 StringBuilder
。如果它可能被多个线程访问,请使用 StringBuffer
(这是罕见的)
Note also that there is StringBuffer
in addition to StringBuilder
. The difference is that the former has synchronized methods. If you use it as a local variable, use StringBuilder
. If it happens that it's possible for it to be accessed by multiple threads, use StringBuffer
(that's rarer)
这篇关于为什么StringBuilder有String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!