版权声明:转载请标明出处 https://blog.csdn.net/weixin_36759405/article/details/82789149
1. String
首先要明确一点,String不属于Java的八大基本数据类型。
String是不可变对象,因此每次在对String类进行改变的都会生成一个新的String对象,然后将指针指向新的String对象。
String.intern方法(Native方法)会在运行时常量池中查找是否存在内容相同的字符串。
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
public native String intern();
}
从上述代码中可以看到String底层是通过字符数组,即char[]实现的。
2. StringBuffer
在对StringBuffer对象进行改变时都是对StringBuffer对象本身进行操作,而不是生成新的对象并改变对象引用,所以多数情况下推荐使用StringBuffer。
StringBuffer线程安全机制:调用的方法添加同步锁synchronized。
public final class StringBuffer extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
/**
* Constructs a string buffer initialized to the contents of the
* specified string. The initial capacity of the string buffer is
* <code>16</code> plus the length of the string argument.
*
* @param str the initial contents of the buffer.
* @exception NullPointerException if <code>str</code> is <code>null</code>
*/
public StringBuffer(String str) {
super(str.length() + 16); //继承父类的构造器,并创建一个大小为str.length()+16的value[]数组
append(str); //将str切分成字符序列并加入到value[]中
}
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
}
3. StringBuilder
StringBuilder提供一个与StringBuffer兼容的API,但不保证同步。
public final class StringBuilder extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
/**
* Constructs a string builder initialized to the contents of the
* specified string. The initial capacity of the string builder is
* <code>16</code> plus the length of the string argument.
*
* @param str the initial contents of the buffer.
* @throws NullPointerException if <code>str</code> is <code>null</code>
*/
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
public StringBuilder append(String str) {
super.append(str);
return this;
}
}
最后强烈建议大家读这三个字符类的源码,最好能够自己动手实现一个String类!!!