String类的subString(i)方法(基于jdk 1.9

2017-10-20  本文已影响30人  kangkaii

只有一个参数的;

String str = new String("ABCD");
System.out.println("str="+str.substring(1));

进入substring()

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

分析:


进入StringLatin1.newString

public static String newString(byte[] val, int index, int len) {
        return new String(Arrays.copyOfRange(val, index, index + len),
                          LATIN1);
}

分析:


再调用 Arrays.copyOfRange

public static byte[] copyOfRange(byte[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        byte[] copy = new byte[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

分析:


最后调用:
System.arraycopy

public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

分析:


综上,str.subString(i) 实际上是

  1. 将 str 转成数组 array01,赋值给一个为新的数组 array02,并且array02.length = str.length - i;
  2. 赋值过程为:array02[0] = array01[i](直到i = array01.length)
  3. array02转换新的String,并返回;

得出结论:subString(i)返回值是 str的索引位置i,到最大索引(两个索引都包括)

上一篇 下一篇

猜你喜欢

热点阅读