前言:之前看ArrayList源码时,碰到了Spliterator,今天就从源码学习一下
Spliterator简介 参考文档Spliterator (Java Platform SE 8 )
Spliterator是Java8新增的一个可分割迭代器(splitable iterator),用于并行处理,集合框架中的数据结构基本都默认实现了spliterator。
Spliterator类图如下
方法 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 32 33 34 public interface Spliterator <T > { boolean tryAdvance (Consumer<? super T> action) ; default void forEachRemaining (Consumer<? super T> action) { do { } while (tryAdvance(action)); } Spliterator<T> trySplit () ; long estimateSize () ; default long getExactSizeIfKnown () { return (characteristics() & SIZED) == 0 ? -1L : estimateSize(); } int characteristics () ; default boolean hasCharacteristics (int characteristics) { return (characteristics() & characteristics) == characteristics; } default Comparator<? super T> getComparator() { throw new IllegalStateException(); } }
特征值 特征值具体代表的含义需要根据不同的实现类分析,不同的实现类,特征值是有区别的,比如ArrayList的内部实现类ArrayListSpliterator,它的特征值分别是ORDERED,SIZED,SUBSIZED
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public static final int ORDERED = 0x00000010 ;public static final int DISTINCT = 0x00000001 ;public static final int SORTED = 0x00000004 ;public static final int SIZED = 0x00000040 ;public static final int NONNULL = 0x00000100 ;public static final int IMMUTABLE = 0x00000400 ;public static final int CONCURRENT = 0x00001000 ;public static final int SUBSIZED = 0x00004000 ;
接口 Spliterator中OfDouble、OfInt、OfLong、OfPrimitive等接口,AbstractLongSpliterator、AbstractDoubleSpliterator等静态抽象类,这里就学习一下OfPrimitive
1 2 3 4 5 6 7 8 9 10 11 12 13 public interface OfPrimitive <T , T_CONS , T_SPLITR extends Spliterator .OfPrimitive <T , T_CONS , T_SPLITR >> extends Spliterator <T > { @Override T_SPLITR trySplit () ; @SuppressWarnings ("overloads" ) boolean tryAdvance (T_CONS action) ; @SuppressWarnings ("overloads" ) default void forEachRemaining (T_CONS action) { do { } while (tryAdvance(action)); } }
泛型,Spliterator.OfPrimitive仅声明了trySplit和tryAdvance方法,提供了forEachRemaining方法的默认实现。
OfPrimitive本质上和Spliterator没有太大的区别,只不过,它限制tryAdvance的参数action类型T_CONS和trySplit的返回参数T_SPLITR必须在实现接口时先声明类型。
OfPrimitive又衍生出了OfInt、OfLong、OfDouble等专门用来处理int数组、Long数组、double数组等分割迭代器接口