1、String字符串类型的数据结构
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
- String是final类型的类,value也是final类型的数组,但这不是String不可变的根本原因,String不可变是因为value是private,且并没有提供对外的get和set。
- 底层char[]数组有final修饰,意味着这个数组不能扩容等,来达到存更多的字符
- char[]数组是私有的,我们程序员无法直接操作这个char[]数组,而且String没有提供这样的方法,来修改char[]数组的元素的值。
2、每次修改,都会产生一个新的字符串
String内的所有涉及对字符数组进行修改的方法,都会重新创建一个字符串对象,将修改后的值放在新String对象中,原字符串不会改变。
(1)String中substring方法:
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); // 产生新的字符串
}
(2)String中的replace()方法的方法:
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true); // 创建新的字符串
}