Java中String、StringBuffer 与StringBuilder的不同

来源:互联网 发布:农村淘宝和快递公司 编辑:程序博客网 时间:2024/06/05 20:18

1、String 是不可变的

String字符串一旦创建不可更改,如下:

public static void main(String[] args) {    String s = "hello";    System.out.println(s);//hello    tell(s);    System.out.println(s);//hello    s= s +"word";    System.out.println(s);//helloword}public static void tell(String s ){    s = "word";    System.out.println(s);//word}

可以看出,定义字符串s为hello后,在堆内存中为“hello”的s分配一块内存,调用tell函数后,又为tell函数中的“word”新分配一块内存,运行S+“word”时,又重新分配了一块内存,调用tell函数后重新输出s,s仍为“hello”。

这里写图片描述

2.StringBuffer 是可变的。

public static void main(String[] args) {    StringBuffer s = new StringBuffer();    s.append("hello");    System.out.println(s.toString());//hello    tell(s);    System.out.println(s.toString());//helloword}public static void tell(StringBuffer s ){    s.append("word");    System.out.println(s.toString());//helloword}

由上面的例子可以看出,StringBuffer是可变的。使用 StringBuffer 类时,每次都会对 StringBuffer 对象本身进行操作,而不是生成新的对象并改变对象引用。所以多数情况下推荐使用 StringBuffer ,特别是字符串对象经常改变的情况下。
3、StringBuilder
一个可变的字符序列。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。但是将 StringBuilder 的实例用于多个线程是不安全的。

0 0
原创粉丝点击