字符串和集合截取

集合的截取方法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  闲杂人等  阅读(346)  评论(0)    收藏  举报

编辑推荐:
· 如何正确实现一个 BackgroundService
· 抽象与性能:从 LINQ 看现代 .NET 的优化之道
· AI 时代,为什么我们还有必要写博客?
· 行业思考:不是前端不行,是只会前端不行
· C#高级GDI+实战:从零开发一个流程图
阅读排行:
· 被 DDoS 攻击的一夜
· 记一次酣畅淋漓的js逆向
· 一个被BCL遗忘的高性能集合:C# CircularBuffer<T>深度解析
· 如何正确实现一个 BackgroundService
· 上周热点回顾(7.28-8.3)

导航

< 2025年8月 >
27 28 29 30 31 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6

统计

点击右上角即可分享
微信分享提示