最近在看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; }
这时就对originalValue.length > size这个不解啊。故网上搜寻原因。发现在*上有人提到这个问题。还有个国内的文章也说了这个问题。
1 http://*.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; }
看看上面的源码,发现使用substring方法后新的String对象的字符数组还是原来对象的字符数组。这样就出现了originalValue.length > size这个问题。如
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。故我们可知在这样的情况下会出现本文讨论的问题。