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

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

首先我们确定一个概念性问题,什么是不可变对象!
什么是不可变对象:如果一个对象,在它创建完成之后,不能再改变它的状态,那么这个对象就是不可变的。不能改变状态的意思是,不能改变对象内的成员变量,包括基本数据类型的值不能改变,引用类型的变量不能指向其他的对象,引用类型指向的对象的状态也不能改变。

String

以下是String的源码截取

** * 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);

从上面我们可以知道每次对String对象的赋值,都是已经改变了String指向的对象!所以String是不可变的!
再深层点,我们会发现里面的data对象是final,所以呢。。呵呵呵
我们也可以很容易理解为什么当用户调用以下语句的时候,会生成了两个对象。
String s = new String("abc");
那么我们可以推出实际编程中String类型的使用时机:常量,数据不会发生改变状态下
StringBuffer和StringBuilder
很多文章都是把StringBuffer和StringBuilder分开来讲解!我觉得这样其实不好,他们区别其实就在于一个关键字:synchronized,这代表着使用StringBuffer是线程安全的,这就决定了他们之间的使用场景,在于多线程和单线程!所以,很简单,如果从使用效率上看,在单线程上跑,使用StringBuilder效率高于StringBuffer,多线程操作(例如网络操作)就用StringBuffer吧!如果考虑到以后扩展的可能性,则更难确定,所以我更愿意使用

StringBuffer。

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

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.

public final class StringBuffer extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
public final class StringBuilder extends AbstractStringBuilder
implements java.io.Serializable, CharSequence

说明StringBuffer是一个线程安全的可变序列!和StringBuilder一样继承了AbstractStringBuilder类,所以StringBuffer和StringBuilder作为Object对象是不能直接比较值的,不管你是用equals还是==,当然==是用来比较内存地址的,如果两个对象引用的是同一个对象,会返回true;
继承了AbstractStringBuilder的可变字符串序列
AbstractStringBuilder提供了对字符串的处理机制,同样是将数据用char数组的类型保存:

/** * 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;
}

在append(str)函数调用的时候,首先会判断原来用于存储字符串的values的字符串数组有没有足够的大小来存储将要新添加入StringBuilder的字符串。如果不够用,那么就调用ensureCapacityInternal判断是否有足够的存储空间,如果够用,那么就直接添加进去,如果不够,那就调用 expandCapacity进行字符串的扩展操作。这是StringBuffer和StringBuilder可变的一个重要原因。
关于字符串更改用+还是append
结果是很明显的!

欢迎工作一到五年的Java工程师朋友们加入Java高并发: 957734884,群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!

猜你喜欢

转载自blog.csdn.net/weixin_44195108/article/details/88699404