String构造器中有一段代码如下:
public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}
其中 originalValue.length > size 这段代码让人有点难以理解,什么情况下会发生呢?
String内部有三个属性
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
subString 方法
public String substring(int beginIndex) {
return substring(beginIndex, count);
}
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);
}
其中value为存放字符的char数组,offset为偏移量,count为长度,当调用subString 方法时会返回一个偏移量为offset + beginIndex,长度为endIndex - beginIndex,value不变(即char数组不变)的String
举个例子:
String a = "012345";
String b = a.substring(2);
String c = new String(b);
其中 a的value为012345的数组,offset为0,coun为6
b的value为012345的数组,offset为2,count为4
当实例化c时就发生了originalValue.length > size即b.value.length>b.count的情况.