String和StringBuffer和StringBuilder的区别
程序员文章站
2024-03-23 14:20:22
...
本章环境java 1.8
String
字符串拼接会重新生成新的字符串
String a= "123";
String a=a+"123";
代码及反编译结果
public class Main{
public static void main(String[] args) {
String str = new String("abc");
}
}
反编译结果
Constant pool:
#1 = Methodref #7.#16 // java/lang/Object."<init>":()V
#2 = Class #17 // Main
#3 = Methodref #2.#16 // Main."<init>":()V
#4 = Class #18 // java/lang/String
#5 = String #19 // abc
#6 = Methodref #4.#20 // java/lang/String."<init>":(Ljava/lang/String;)V
#7 = Class #21 // java/lang/Object
#8 = Utf8 <init>
#9 = Utf8 ()V
#10 = Utf8 Code
#11 = Utf8 LineNumberTable
#12 = Utf8 main
#13 = Utf8 ([Ljava/lang/String;)V
#14 = Utf8 SourceFile
#15 = Utf8 Main.java
#16 = NameAndType #8:#9 // "<init>":()V
#17 = Utf8 Main
#18 = Utf8 java/lang/String
#19 = Utf8 abc
#20 = NameAndType #8:#22 // "<init>":(Ljava/lang/String;)V
#21 = Utf8 java/lang/Object
#22 = Utf8 (Ljava/lang/String;)V
当new String("abc")时,其实会先在字符串常量区生成一个abc的对象,然后new String()时会在堆中分配空间,然后此时会把字符串常量区中abc复制一个给堆中的String(这里不是很清楚,是复制还是引用??),故abc应该在堆中和字符串常量区。
StringBuffer&StringBuilder
都是继承AbstractStringBuilder实现
所以扩容的方式也是利用AbstractStringBuilder的扩容方式,2n+2的方式扩容
void expandCapacity(int minimumCapacity) {
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0)
newCapacity = minimumCapacity;
if (newCapacity < 0) {
if (minimumCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity);
}
常用方法
- 获得某个位置上的字符s.charAt(1)
- 修改某个位置上的字符s.setCharAt(1,'1')
- 后缀字符串s.append("11")
不同点
StringBuffer是线程安全,对大部分方法使用synchronized修饰,如:append方法
StringBuilder是线程不安全
上一篇: JAVA面试宝典
推荐阅读
-
string,stringbuffer和stringbuilder的区别详解
-
String、StringBuffer和StringBuilder的区别
-
String和StringBuffer和StringBuilder的区别
-
String、StringBuffer和StringBuilder的区别
-
toString()、new String()和(String) 、String.ValueOf()的区别
-
基础类型和引用类型的区别
-
define和inline的区别
-
String和StringBuilder、StringBuffer的区别?
-
c语言函数声明中,static inline和extern inline的区别
-
string.valueof和toString的区别