java String中关于substring的源码分析

最近在使用java String中的方法substring(index)时发现传入一个参数index时,当index = str.length()并不报错,且返回一个空字符串。于是查阅了一下java的源代码,才发现原来如此:

substing()源码:


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);
    }
可知只要 sublen可以为零,而new String()又是怎么工作的呢?

看以下的代码:

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;
                return;
            }
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    

当count等于0的时候如果offset <= value.length 则生成一个空串;

猜你喜欢

转载自blog.csdn.net/qq_36561697/article/details/80365540