字符串和集合截取

集合的截取方法subList(int fromIndex, int toIndex) 底层的实现方法是:

SubList(AbstractList<E> list, int fromIndex, int toIndex) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
        l = list;
        offset = fromIndex;
        size = toIndex - fromIndex;
        this.modCount = l.modCount;
    }

截取的长度是size = toIndex - fromIndex; 也就是说从fromIndex开始(包括这个位置的字符)截取长度是size的字符串,最直白的讲我们可以认为截取的时候是不包括最后位置是toIndex的字符的。

 

字符串的截取方法:String substring(int beginIndex, int endIndex) 底层的实现方法是:

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

这个原理跟集合的截取是一样的

posted on 2018-03-08 11:19  闲杂人等  阅读(337)  评论(0编辑  收藏  举报

导航