substring:"A".substring(1)不报异常的分析来源: 发布时间:星期四, 2008年10月16日 浏览:2次 评论:0
我看到代码"A".substring(1);我第一眼觉得应该越界,因为我基础不好,但是结果没有问题,是个空,我想请您指点迷津
我第一眼也是有问题,因为字符串的长度只有1,而且是从0开始编号的。 还是去看看源代码吧 public String substring(int beginIndex) { return substring(beginIndex, count); } 其中的count没有悬念,是字符串的字符长度,对于我们的例子,长度就是1. 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); } 可见,系统是起始的位置如果大于结束的位置,此处结束位置就是字符串的长度1 而我们写的起始位置等于字符串长度,没有大于结束位置,所以不会报异常。 如果写成 "A".substring(2) 则由于超过了字符串的长度1,报 StringIndexOutOfBoundsException 0
相关文章读者评论
发表评论 |