源码:
1 public String(char value[], int offset, int count) { 2 if (offset < 0) { 3 throw new StringIndexOutOfBoundsException(offset); 4 } 5 if (count <= 0) { 6 if (count < 0) { 7 throw new StringIndexOutOfBoundsException(count); 8 } 9 if (offset <= value.length) { 10 this.value = "".value; 11 return; 12 } 13 } 14 // Note: offset or count might be near -1>>>1. 15 if (offset > value.length - count) { 16 throw new StringIndexOutOfBoundsException(offset + count); 17 } 18 this.value = Arrays.copyOfRange(value, offset, offset+count); 19 }
char[] value: 用于构造字符串的数组内容
int offset: 偏移量,即从数组的offset位置开始复制
int count: 复制元素的个数
解析:
1. offset < 0, 直接抛异常
2. 当count <= 0时, 进行处理: 如果count <0 抛异常, 那么接下来第9行的if执行的为 count = 0,此时如果offset <= value.length(即offset的数值是合法的,在0 ~ length之间),那么构造的字符串的内容等于"".value(因为count = 0,复制0个就是空字符串了)
3. 对value数组本身的内容进行检查,假如offset + count > value.length 就抛异常,因为要复制的内容并不足够,注意在该if中,条件的书写为: offset > value.length - count,
给出的原因是,offset 或者 count 可能在 -1 >>> 1附近,即int的最大值附近, 因为这两个变量都是int类型值,这样的话,两者相加将很可能溢出,从而导致错误,而转换之后,解决了两者相加溢出的问题.