继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【Java】从源码角度分析String,StringBuffer和StringBuilder

倚天杖
关注TA
已关注
手记 182
粉丝 46
获赞 185

很多人都知道String是不可变的,StringBuffer和StringBuilder是可变的,那么为什么呢?

首先我们确定一个概念性问题,什么是不可变对象
什么是不可变对象:如果一个对象,在它创建完成之后,不能再改变它的状态,那么这个对象就是不可变的。不能改变状态的意思是,不能改变对象内的成员变量,包括基本数据类型的值不能改变,引用类型的变量不能指向其他的对象,引用类型指向的对象的状态也不能改变。
String
以下是String的源码截取
<pre>
** * The {@code String} class represents character strings. All * string literals in Java programs, such as {@code "abc"}, are
implemented as instances of this class.  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. For example:  String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'}; *
String str = new String(data);
</pre>
从上面我们可以知道每次对String对象的赋值,都是已经改变了String指向的对象!所以String是不可变的!
再深层点,我们会发现里面的data对象是final,所以呢。。呵呵呵
我们也可以很容易理解为什么当用户调用以下语句的时候,会生成了两个对象。<pre>String s  = new String("abc");</pre>

那么我们可以推出实际编程中String类型的使用时机:常量,数据不会发生改变状态下

StringBuffer和StringBuilder
很多文章都是把StringBuffer和StringBuilder分开来讲解!我觉得这样其实不好,他们区别其实就在于一个关键字:synchronized,这代表着使用StringBuffer是线程安全的,这就决定了他们之间的使用场景,在于多线程和单线程!所以,很简单,如果从使用效率上看,在单线程上跑,使用StringBuilder效率高于StringBuffer,多线程操作(例如网络操作)就用StringBuffer吧!如果考虑到以后扩展的可能性,则更难确定,所以我更愿意使用StringBuffer。

下面我们分析下StringBuffer和String的区别~
<pre>

  • 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.
    </pre>
    <pre>public final class StringBuffer extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
    public final class StringBuilder extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
    </pre>

说明StringBuffer是一个线程安全的可变序列!和StringBuilder一样继承了AbstractStringBuilder类,所以StringBuffer和StringBuilder作为Object对象是不能直接比较值的,不管你是用equals还是==,当然==是用来比较内存地址的,如果两个对象引用的是同一个对象,会返回true;

继承了AbstractStringBuilder的可变字符串序列
AbstractStringBuilder提供了对字符串的处理机制,同样是将数据用char数组的类型保存:
<pre>
/** * Appends the specified string to this character sequence. * <p> * The characters of the {@code String} argument are appended, in * order, increasing the length of this sequence by the
length of the * argument. If {@code str} is {@code null}, then the four * characters {@code "null"} are appended. * <p> * Let <i>n</i> be the length of this character sequence just prior to * execution of the {@code append} method. Then the character
at * index <i>k</i> in the new character sequence is equal to the character * at index <i>k</i> in the old character sequence, if <i>k</i>
is less * than <i>n</i>; otherwise, it is equal to the character at index * <i>k-n</i> in the argument {@code str}. * *
@param   str   a string. * @return  a reference to this object. */

public AbstractStringBuilder append(String str) {
if (str == null) return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
</pre>
在append(str)函数调用的时候,首先会判断原来用于存储字符串的values的字符串数组有没有足够的大小来存储将要新添加入StringBuilder的字符串。如果不够用,那么就调用ensureCapacityInternal判断是否有足够的存储空间,如果够用,那么就直接添加进去,如果不够,那就调用 expandCapacity进行字符串的扩展操作。这是StringBuffer和StringBuilder可变的一个重要原因。

关于字符串更改用+还是append
结果是很明显的!有一篇文章写得不错<a href = "http://www.blogjava.net/nokiaguy/archive/2008/05/07/198990.html">在Java中连接字符串时是使用+号还是使用StringBuilder</a>

喜欢就给我点个赞呗!



作者:MarcoHorse
链接:https://www.jianshu.com/p/60c1572e6074


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP