A method defined by Spliterator

A constant graph defined in the interface

ArrayList ArrayListSpliterator source code analysis

@Override public Spliterator<E> spliterator() { return new ArrayListSpliterator<>(this, 0, -1, 0); } static final class ArrayListSpliterator<E> implements Spliterator<E> {private final ArrayList<E> list; // Start position (included), advance/split will change private int index; // End position (not included), -1 to the last element private int fence; Private int expectedModCount private int expectedModCount; ArrayListSpliterator(ArrayList<E> list, int origin, int fence, int expectedModCount) { this.list = list; this.index = origin; this.fence = fence; this.expectedModCount = expectedModCount; } private int getFence() {expectedModCount = expectedModCount; ArrayList<E> lst; // When the fence<0 (the first initialization, the fence is less than 0) : If ((LST = list) == null) {// If (LST = list) == null) Else {// otherwise, fence = the length of list. expectedModCount = lst.modCount; hi = fence = lst.size; } } return hi; } // Split list, Public ArrayListSpliterator<E> trySplit() {//hi for the current end position //lo for the start position // compute the middle position int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; // If lo>=mid, index=mid return (lo >=mid)? // If lo<mid, index=mid return (lo >=mid)? null : new ArrayListSpliterator<E>(list, lo, index = mid, expectedModCount); } // Return true to indicate that there may be some elements left unprocessed // Return false to indicate that there are no elements left to process... public boolean tryAdvance(Consumer<? super E> action) { if (action == null) throw new NullPointerException(); Int hi = getFence(), I = index; If (I < hi) {// if (I < hi) {// If (I < hi) { @SuppressWarnings("unchecked") E e = (E)list.elementData[i]; action.accept(e); If (list.modcount! = expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } public void forEachRemaining(Consumer<? super E> action) { int i, hi, mc; // hoist accesses and checks from loop ArrayList<E> lst; Object[] a; if (action == null) throw new NullPointerException(); if ((lst = list) ! = null && (a = lst.elementData) ! When the fence<0, the fence and the expectedModCount are not initialized, so can you call getFence() directly? if ((hi = fence) < 0) { mc = lst.modCount; hi = lst.size; } else mc = expectedModCount; if ((i = index) >= 0 && (index = hi) <= a.length) { for (; i < hi; ++i) { @SuppressWarnings("unchecked") E e = (E) a[i]; // Call action.accept to handle the element action.accept(e); If (lst.modcount == MC) return; } } throw new ConcurrentModificationException(); } public long estimateSize() {return (long) (getFence() -index); } // public int characteristics() {// public int characteristics() { And can return the size return Spliterator. ORDERED | Spliterator. SIZED | Spliterator. SUBSIZED; }}Copy the code

The implementation class diagram