String, StringBuffer, StringBuilder三者的使用和区别

本文详细解析了Java中的String、StringBuffer和StringBuilder的区别与应用场景。探讨了它们的特性,如String的不可变性和线程安全性,StringBuffer的线程安全机制,以及StringBuilder在单线程下的性能优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、String的使用

             首先,String不是基本数据类型,曾经记混了,看一下源码介绍:

Strings are constant; their values cannot be changed after they
* are created. String buffers support mutable strings.
* Because String objects are immutable they can be shared. 

 

String是一个常量,创建后其值不能改变,StringBuffer支持可变字符串, 因为String对象不可变,所以可以共享,所以是线程安全的

但是我们经常在代码中改变String的值,这明显与上文说的有冲突,例如:

String s1 = “a”;

s1 = s1 + "b";

System.out.print(s1);

输出的是ab;

实际上,java虚拟机在实现该段代码时的具体操作为:首先创建s1, 并将其赋值为“a”,然后又新创建一个s1赋值为之前的s1+“b”(可以通过打印两个对象的hashCode值,来进行验证),此时之前的s1被销毁,如果多进行几次赋值操作,势必会创建和销毁多个对象, 这明显非常浪费内存,所以String在三者中,执行速度是最慢的

 

二、StringBuffer的使用

            

* A thread-safe, mutable sequence of characters.
* A string buffer is like a {@link String}, but can be modified. At any
* point in time it contains some particular sequence of characters, but
* the length and content of the sequence can be changed through certain
* method calls.

一个线程安全的,可变字符串,字符串的长度和内容都可以改变

相比于String来说,StringBuffer在创建和改变时不会多次创建新的对象,所以执行速度比String快,但由于进行了线程同步,所以相对于线程不安全的StringBuilder来说,速度较慢

 

 

三、StringBuilder的使用

 A mutable sequence of characters.  This class provides an API compatible
* with {@code StringBuffer}, but with no guarantee of synchronization.
* This class is designed for use as a drop-in replacement for
* {@code StringBuffer} in places where the string buffer was being
* used by a single thread (as is generally the case).   Where possible,
* it is recommended that this class be used in preference to
* {@code StringBuffer} as it will be faster under most implementations.

大致意思是: 一个可变的字符串,没有进行线程同步,在单线程情况下通常用来代替StringBuffer,因为他比StringBuffer更快

总结:

        操作少量数据,用String

        单线程下操作大量数据,用StringBuilder

        多线程下操作大量数据,用StringBuffer

   

String的进一步讨论 :

    String s1 = new String("s1");

    String s2 = new String("s1");

    上述代码创建了几个对象?

    答:三个, 编译期,常量池中创建了一个常量"s1";

                        运行期, 堆内存中创建了两个对象,s1和s2;

    

 

借鉴了http://blog.youkuaiyun.com/chenliguan/article/details/51911906

和http://blog.youkuaiyun.com/vfush/article/details/53038437,如有侵权,请立即告知

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值