在Java语言中,String和StringBuffer有什么不同?
字符串有最大长度限制吗?
发布于 2013-03-22 14:54:16
String StringBuffer
Immutable Mutable
String s=new String("karthik"); StringBuffer sb=new StringBuffer("karthik")
s.concat("reddy"); sb.append("reddy");
System.out.println(s); System.out.println(sb);
O/P:karthik O/P:karthikreddy
--->once we created a String object ---->once we created a StringBuffer object
we can't perform any changes in the existing we can perform any changes in the existing
object.If we are trying to perform any object.It is nothing but mutablity of
changes with those changes a new object of a StrongBuffer object
will be created.It is nothing but Immutability
of a String object
Use String--->If you require immutabilty
Use StringBuffer---->If you require mutable + threadsafety
Use StringBuilder--->If you require mutable + with out threadsafety
String s=new String("karthik");
--->here 2 objects will be created one is heap and the other is in stringconstantpool(scp) and s is always pointing to heap object
String s="karthik";
--->In this case only one object will be created in scp and s is always pointing to that object only
发布于 2011-03-05 00:58:25
String是一个不可变的类。这意味着一旦你像这样实例化了一个字符串的实例:
String str1 = "hello";
内存中的对象不能更改。相反,您必须创建一个新的实例,复制旧的字符串并附加任何其他内容,如本例所示:
String str1 = "hello";
str1 = str1 + " world!";
实际发生的情况是,我们没有更新现有的str1对象...我们一起重新分配新的内存,复制"hello“数据并附加”world!“最后,将str1引用设置为指向这个新内存。因此,它看起来更像是这样的:
String str1 = "hello";
String str2 = str1 + " world!";
str1 = str2;
因此,这个“复制+粘贴并在内存中到处移动东西”的过程如果重复地完成,特别是递归地完成,可能会非常昂贵。
当您处于不得不一遍又一遍地做事情的情况下,请使用StringBuilder。它是可变的,可以将字符串附加到当前字符串的末尾,因为它是由growing array返回的。
发布于 2010-03-14 01:27:03
StringBuffer用于从多个字符串创建单个字符串,例如,当您想要在循环中附加字符串的部分时。
当只有一个线程访问StringBuffer时,您应该使用StringBuilder而不是StringBuffer,因为StringBuilder不是同步的,因此速度更快。
AFAIK在作为一种语言的Java中,字符串大小没有上限,但JVM可能有上限。
https://stackoverflow.com/questions/2439243
复制相似问题