首先先看一下本次解读substring的构造方法
public String substring(int beginIndex) {
// 传递进来的就是使用substring开始截取的索引值
if (beginIndex < 0) {
// 进行判断如果传递进来的索引值小于等于0就索引越界异常
throw new StringIndexOutOfBoundsException(beginIndex);
}
// 这里的value是调用substring的值其底层是一个数组,
// 获取到截取后的长度,判断如果小于0就抛出异常
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
// 注意:这里的this指的是调用者对象!,接着我们继续读new String(value,beginIndex,subLen)
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
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的意思是指初始化一个空的字符串,这是一个String对象
this.value = "".value;
return;
}
}
if (offset > value.length - count) {
/*
上面已经介绍了三个参数的意思这里就很好理解了,如果总长度减去要
截取的长度小于开始截取的索引值那么就会索引越界
*/
throw new StringIndexOutOfBoundsException(offset + count);
}
/*
最后offset+count的意思就是为了寻找截取结束的索引值,结合substring的单参数构造方法来看
该单个参数的方法截取是包头包尾的
*/
this.value = Arrays.copyOfRange(value, offset, offset+count);
}