zoukankan      html  css  js  c++  java
  • 字符串和集合截取

    集合的截取方法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;
        }

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

  • 相关阅读:
    C#图解教程学习笔记——类和继承
    C#图解教程学习笔记——类相关的概念
    C#图解教程学习笔记——方法
    C#图解教程学习笔记——数据类型与数据存储
    模板方法模式
    命令模式
    访问者模式
    观察者模式
    策略模式
    单体【其他模式】
  • 原文地址:https://www.cnblogs.com/programmer1/p/8527311.html
Copyright © 2011-2022 走看看