String类为什么不可改变(immutable)?
首先它是包装了基本数据类型char的字符数组类,在字符数组定义的时候就开辟好了固定的空间,所以你无法再改变它的内容;其次String类定义属性
时使用的final修饰,所以一旦设置好初始化内容后,作为常量,内容不可改变。
/** The value is used for character storage. */
private final char value[];
String类常用方法:
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
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;
}