最近观看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这个不解啊。故网上搜寻原因。

发如今stackoverflow上有人提到这个问题。

原来是这样啊。来看看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。

故我们可知在这种情况下会出现本文讨论的问题。