标签:
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; /* avoid getfield opcode */ int off = offset; /* avoid getfield opcode */ 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操作
都不是在原有的字符串上进行的,而是重新生成了一个新的字符串对象。
也就是说进行这些操作后,最原始的字符串并没有被改变。
标签:
原文地址:http://www.cnblogs.com/chengbao/p/5183825.html