對(duì)String類(lèi)的討論已經(jīng)是老生常談了,最權(quán)威的莫過(guò)于源碼谴餐,今天就來(lái)看下String源碼姻政。基于JDK1.8岂嗓。
支持原創(chuàng)汁展,轉(zhuǎn)載請(qǐng)注明出處。
繼承關(guān)系
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
成員變量
private final char value[]; //private, final修飾確保不會(huì)被外界引用,且所有操作不會(huì)修改數(shù)組的值食绿,這是String常量性質(zhì)的保證
private int hash; // Default to 0
構(gòu)造方法
public String() {
this.value = new char[0];
}
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// 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);
}
構(gòu)造函數(shù)都很直觀侈咕。
charAt方法
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
很直觀,直接返回下標(biāo)對(duì)應(yīng)的字符器紧。
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); //創(chuàng)建一個(gè)新的String對(duì)象
}
該方法耀销,首先檢查參數(shù)是否合法,若合法铲汪,則創(chuàng)建一個(gè)新的String對(duì)象熊尉,期間伴隨著拷貝操作。
replace方法
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) { //新老字符不相等直接方法當(dāng)前對(duì)象
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) { //尋找第一個(gè)oldChar
break;
}
}
if (i < len) { //存在oldChar
char buf[] = new char[len];
for (int j = 0; j < i; j++) { //原封不動(dòng)拷貝i之前的字符
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c; //用新字符替換舊字符
i++;
}
return new String(buf, true); //創(chuàng)建新的字符串掌腰,并返回
}
}
return this;
}
該方法尋找第一個(gè)oldChar下標(biāo)i狰住,如果存在oldChar,則新建一個(gè)字符數(shù)組buf齿梁,拷貝i之前的字符到新字符數(shù)組催植,i之后用新字符替換舊字符。用buf新建String對(duì)象士飒,并返回查邢。
總結(jié)
String的常量性質(zhì)來(lái)源于private final char value[]
,并且所有操作中都不會(huì)直接修改value這個(gè)數(shù)組酵幕。
支持原創(chuàng)扰藕,轉(zhuǎn)載請(qǐng)注明出處。
github:https://github.com/gatsbydhn