今天收到网友
不懂装懂 的来信
您好,讨论个问题
我看到代码"A".substring(1);我第一眼觉得应该越界,因为我基础不好,但是结果没有问题,是个空,我想请您指点迷津
我第一眼也是有问题,因为字符串的长度只有1,而且是从0开始编号的。
还是去看看源代码吧
其中的count没有悬念,是字符串的字符长度,对于我们的例子,长度就是1.
可见,系统是起始的位置如果大于结束的位置,此处结束位置就是字符串的长度1
而我们写的起始位置等于字符串长度,没有大于结束位置,所以不会报异常。
如果写成
则由于超过了字符串的长度1,报
StringIndexOutOfBoundsException
原文地址:http://www.java2000.net/p10866
您好,讨论个问题
我看到代码"A".substring(1);我第一眼觉得应该越界,因为我基础不好,但是结果没有问题,是个空,我想请您指点迷津
我第一眼也是有问题,因为字符串的长度只有1,而且是从0开始编号的。
还是去看看源代码吧
- 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);
- }
而我们写的起始位置等于字符串长度,没有大于结束位置,所以不会报异常。
如果写成
- "A".substring(2)
StringIndexOutOfBoundsException
原文地址:http://www.java2000.net/p10866