文章目录
概要
在学习java的第一课就听过,Java中String对象是不可变的,今天就来聊聊String在源码层面是如何实现不可变的
不可变设计
1、String对象使用final进行修饰
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
在String
类级别的修饰符使用了final
修饰符,意味着String
类不能被其他的任何类继承,也就无法重写此类的任何方法。String类的语意是不可变,所以独立成不可继承类,以免由于继承问题带来的歧义(个人理解,String
类的很多方法必须要用public
修饰,如果允许继承的话 ,子类无法保证不可变 的语意,导致写成多态的时候有歧义认为String
是可变的)
2、String对象内部成员变量value[]是final+private修饰,在初始化的时候就已确定,不能改变。
private final char value[];
String
字符串的所有操作底层都是基于value
这个数组来实现的,本质上的字符串是个char
的数组,所以很明显修改保证value[]
不能被改变。
1、使用final
修饰的成员变量无法通过反射再次赋值。String
类所有的构造方法都会对value
进行赋值 ,就算使用了反射也不能再次改变value
的值
2、final
修饰后引用不能改变,这就防止value
会被不断的赋值的可能从而打破String
设计不可变的语意。这里有人会说,虽然final修饰的变量不能再次赋值,但是value引用数组本身的值是可以改变的,一但value
改变了,那么这个语意也无法保证。说得不错,如果只是使用final
进行修饰还不够,请接着往下看它是如何处理的。
3、String类所有的写操作都是返回新的字符串,而非直接修改value[]的值。
String
类中所有的写操作都会返回新的字符串,分析两个常用的方法。读操作本质上不改变value[]
的值所以不破坏不可变的语意。
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
String
的substring
相信大家再熟悉不过了,源码实现非常简单。可以看到,对于String
的写操作,是返回了一个新的String
对象,这里的value
作为构造传入值,点进去看它到底有没有被修改
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
可以看到,虽然传递的value[]
引用,但是只是发生了copy动作而没有直接改变原始的value[]值。
我们再看看replace
方法
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
同样,replace
方法也是没有改变底层value[]的值,而是重新生成了一个新的String对象
你是否犯过这样的错误?
public static void main(String[] args) {
String name = "abc";
name.replace("a", "b");
System.out.println(name);
}
name输出并非是你期望的bbc,还是abc。这里就是没理解到String
对象本质上是不可变设计,所有的写操作都会生成新的字符串对象。所以针对String
的replace、substring
这些方法调用完之后要使用新的变量来接收它。