String值的不变性
/** The value is used for character storage. */
private final char value[];
String s="zxk";
s="rust";
这个s变量的值发生了改变吗?
答案是并没有,我们可以翻出源码来看一下
/** The value is used for character storage. */
private final char value[];
这个value数组的定义是一个常量的数组,那怎么可能s变量发生改变了嘛?
但是确实s,输出出来的是rust,没错。
首先可以看上面两张图,第一张s的对象地址在542,第二张s对象的地址在544,可以看出,s的内容并没有发生改变,只是对象发生了变化,也可以说s不再是当初那个s了。
equals方法
Equals方法写的也很清晰,比较两个字符串。
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
//
public boolean equals(Object anObject) {
//引用同一个类型
if (this == anObject) {
return true;
}
//anObject是否是String类型
if (anObject instanceof String) {
//强制转换
String anotherString = (String)anObject;
//获取长度
int n = value.length;
//假如长度一致
if (n == anotherString.value.length) {
//转换成字符数组
char v1[] = value;
//转换成字符数组
char v2[] = anotherString.value;
int i = 0;
//比较
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
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;
}