字符串和集合截取

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

编辑推荐:
· 独立开发,这条路可行吗?
· 我在厂里搞 wine 的日子
· 如何通过向量化技术比较两段文本是否相似?
· 35+程序员的转型之路:经济寒冬中的希望与策略
· JavaScript中如何遍历对象?
阅读排行:
· C#源生成器:让你的代码飞起来的黑科技
· JavaScript面试题,为什么[] + 0 = '0', 而{} + 0 = 0?
· 简单记录下最近2个月完成的线上系统迁移工作
· 推荐 5 款实用的 Docker 可视化管理工具,工作效率翻倍!
· 转岗运维第一集:手把手教你完成Nginx-HTTPS证书全生命周期

导航

< 2025年7月 >
29 30 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 7 8 9
点击右上角即可分享
微信分享提示