package chengbaoDemo;
import java.util.Arrays;
/**
*需求:數組的擴容以及數據的拷貝
*分析:因為String的實質是以字符數組存儲的,所以字符串的追加,<br>
*實質上是數組的擴容,數據的移動(復制)
*
*/
public class TestString {
public static void main(String[] args) {
String src = new String("src");
String app = new String("app");
String newString = copy(src, app);
System.out.println(newString);
}
public static String copy(String src, String app) {
char srcArray[] = src.toCharArray();
/*(1)創建一個新的字符數組,數組的大小為原字符串的長度 + 追加的字符串長度,
並將原字符串拷貝到新數組中*/
//這個方法是Arrays類的靜態方法
char[] buf = Arrays.copyOf(srcArray, src.length() + app.length());
//(2)復制追加字符串的字符到新字符數組中,注意: 源對象和目的對象都是字符數組
//這個方法是System
System.arraycopy(app.toCharArray(), 0, buf, src.length(), app.length());
//(3)返回新字符串
return new String(buf);
}
}
注意:String類是final, 是不可繼承,不可以改變的;
所以字符串的追擊,修改才做都不是在原字符串上修改,而是創建一個新的字符串,
講原字符串,和追加的字符串數據,拷貝到行的字符串數組,
實質:是數組的擴容,數據的移動
如下面幾個String類的方法
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value;
int off = offset;
while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
結論:
從上面的三個方法可以看出,無論是sub操、concat還是replace操作
都不是在原有的字符串上進行的,而是重新生成了一個新的字符串對象。
也就是說進行這些操作后,最原始的字符串並沒有被改變。