集合的截取方法subList(int fromIndex, int toIndex) 底層的實現方法是:this
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的字符的。spa
字符串的截取方法:String substring(int beginIndex, int endIndex) 底層的實現方法是:code
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; }
這個原理跟集合的截取是同樣的blog