Java中的String和StringBuffer有什么区别? [英] What is the difference between String and StringBuffer in Java?
问题描述
Java中String和StringBuffer有什么区别?
What is the difference between String and StringBuffer in Java?
String的最大大小是什么?
Is there a maximum size for String?
推荐答案
字符串
用于处理无法更改的字符串(只读和不可变)。
String
is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer
用于表示可以修改的字符。
StringBuffer
is used to represent characters that can be modified.
性能方面, StringBuffer
在执行连接时速度更快。这是因为当你连接一个 String
时,你每次都在(内部)创建一个新对象,因为 String
是不可变的。
Performance wise, StringBuffer
is faster when performing concatenations. This is because when you concatenate a String
, you are creating a new object (internally) every time since String
is immutable.
您还可以使用 StringBuilder
,类似于 StringBuffer
除了它没有同步。其中任何一个的最大大小是 Integer.MAX_VALUE
(2 31 - 1 = 2,147,483,647)或最大堆大小除以2(参见 Java String有多少个字符?)。
更多信息此处。
You can also use StringBuilder
which is similar to StringBuffer
except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE
(231 - 1 = 2,147,483,647) or maximum heap size divided by 2 (see How many characters can a Java String have?).
More information here.
这篇关于Java中的String和StringBuffer有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!