public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
该方法实际是通过Arrays.copyOfRange实现,
不同点在于,该处代码之前的 if (offset > value.length - count) 语句,让该方法无法越界创建char[ ]。
如:
char[] t1=Arrays.copyOfRange(chars,4,14);
//String s1=new String(chars,4,10);
chars[10],offset=4,count=10,
使用该方法运行到if (offset > value.length - count) 发生越界报错,因为数组剩余的长度是6,而要创建的子数组长度是10。
直接使用Arrays.copyOfRange可以创建出长度为8的数组,下面的代码,
Math.min(original.length - from, newLength) 此时拷贝的长度是6,copy数组的长度是10,其中因为越界没有拷贝的2个元素被填充默认值‘\u0000’。
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}