This question already has answers here:
Why is “out of range” not thrown for 'substring(startIndex, endIndex)'
                                
                                    (6个答案)
                                
                        
                                12个月前关闭。
            
                    
为什么"a".substring(1)不是throw StringIndexOutOfBoundsException,而对于大于等于2的索引却为什么呢?真的很有趣。

提前致谢!

最佳答案

您将在源代码中得到答案:

 public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }


其中value.length为1的条件

int subLen = value.length - beginIndex;


它将变成:
int subLen = 1-1;
并且subLen将为0,因此if (subLen < 0) {将为false,并且不会引发异常:)

关于java - substring(int)方法神奇地不会引发StringIndexOutOfBoundsException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24909685/

10-13 04:07