最近在看Jdk6中String的源碼的時候發現String的有個這樣的構造方法,源代碼內容如下:
public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { int off = original.offset; v = Arrays.copyOfRange(originalValue, off, off+size); } else { v = originalValue; } this.offset = 0; this.count = size; this.value = v; }
1 http://stackoverflow.com/questions/12907986/how-could-originalvalue-length-size-happen-in-the-string-constructor
2 http://www.kankanews.com/ICkengine/archives/99041.shtml
看了上面的兩篇文章的說明,我徹底的明白了。原來是這樣啊。來看看jdk6中String的subString方法。
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); }
// Package private constructor which shares value array for speed. String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; }
String s1="hello world"; String s2=s1.substring(6); String s3=new String(s2);分析上面的代碼 s2的屬性char[] value任然是原來s1的屬性char[] value={'h','e','l','l','o',' ','w','o','r','l','d'}。s2的屬性offset為6,count為5.在new String(s2)時originalValue.length=11>count=5。故我們可知在這樣的情況下會出現本文討論的問題。