Iterator and Spliterator

作者: gattonero | 来源:发表于2019-02-02 09:29 被阅读0次

    Iterator

    Java中有三种Iterator,Enumeration,Iterator,ListIterator

    • Enumeration ,一种用于遍历旧式数据结构的Iterator,比如Vector和Hashtable(一种同步哈希表),也可以用于SequenceInputStream(用于合并输入流,顺序读取)
    //add 10 elements for test
    Vector v = new Vector(); 
    for (int i = 0; i < 10; i++) v.addElement(i); 
    
    Enumeration e = v.elements(); 
      
    // Checking the next element availability 
    while (e.hasMoreElements()) 
    { 
        // moving cursor to next element 
       int i = (Integer)e.nextElement(); 
       System.out.print(i + " "); 
    } 
    
    • Iterator 通用的Iterator,可用于任何Collection对象,相比于Enumeration,在遍历时可进行读取和删除操作,下面列出了Iterator的基本方法
    Iterator iterator = collection.iterator();
    iterator.hasNext();//boolean
    iterator.next();//Object
    iterator.remove()//void
    

    缺陷:不能新增或者替换元素,而且只能单向遍历

    • ListIterator
      只适用于List集合,比如ArrayList,LinkedList,不过该接口提供双向遍历:
    listIterator.hasPrevious();//boolean
    listIterator.previous();//Object
    listIterator.previousIndex();//int
    listIterator.set();//void replace the last element find by next() or previous()
    listIterator.add()//void add element before the element which will be returned by next()
    

    ListIterator没有当前元素,当前指针的位置始终在next()和previous()两个元素之间

    Spliterators

    Spliterators 和其他的 Iterators一样,都是遍历数据源的手段,包括CollectionsIO ChannelGenerator function
    它除了支持顺序遍历之外,添加了Java 8对于并行的支持

    每一个Spliterator的特性都不同,可能的值有

    ORDERED(0x00000010), DISTINCT(0x00000001), SORTED(0x00000004), SIZED(0x00000040), NONNULL(0x00000100), IMMUTABLE(0x00000400), CONCURRENT(0x00001000), SUBSIZED(0x00004000).
    

    针对不同的特性,characteristics()返回位编码下的特性int值,hasCharacteristics检测是否拥有该特性

    //simple bitwise operation
    default boolean hasCharacteristics(int characteristics) {
      return (characteristics() & characteristics) == characteristics;
    }
    

    其中tryAdvance() 方法将next()和hasNext()结合起来,并且可以通过forEachRemaining(Consumer),简单的对Iterator的剩余元素进行遍历

    除此之外,还可以使用estimateSize和getExactSizeIfKnown来估计遍历对象的大小

    // Create an array list for doubles. 
    ArrayList<Integer> al = new ArrayList<>(); 
          
    // Add values to the array list. 
    al.add(1); 
    al.add(2); 
    al.add(-3); 
    al.add(-3); 
    al.add(-4); 
    al.add(5); 
    
    Stream<Integer> str1 = al.stream(); 
    Spliterator<Integer> splitr1 = str1.spliterator(); 
    System.out.println(splitr1.characteristics());
    //结合hasNext和next方法
    splitr1.tryAdvance((a) -> System.out.println(a+"!"));
    
    // trySplit()  将剩余元素分成两部分,取出第一部分
    Spliterator<Integer> splitr2 = splitr1.trySplit(); 
    splitr2.forEachRemaining((a) -> System.out.println(a));
    splitr1.forEachRemaining((a) -> System.out.println(a));
    

    结果

    16464
    1!
    2
    -3
    -3
    -4
    5
    

    Tips

    • 16464 = 0x4050 = 0x4000+0x0010+0x0040=SUBSIZED+SIZED+ORDERED
    • Even an inexact estimate is often useful and inexpensive to compute. 估计遍历器大小的操作并不昂贵
    • The characteristics of a given spliterator before splitting may differ from the characteristics after splitting,For specific examples see the characteristic values SIZED, SUBSIZED and CONCURRENT. spliterator的characteristics在split前后可能不同,详见上述几个特性
    • 任何Iterator的引用在初始化时,下标都会指向首元素之前
    • 上述的三个Iterator只是不同的接口,需要在具体的类中,通过诸如elements(), iterator(), listIterator()等方法实现,一般是通过匿名内部类来实现的
    System.out.println(new java.util.Vector().elements().getClass().getName());//java.util.Vector$1
    

    Ref

    https://www.geeksforgeeks.org/java-util-interface-spliterator-java8/
    https://blog.csdn.net/java4found/article/details/8656594
    https://www.geeksforgeeks.org/iterators-in-java/

    相关文章

      网友评论

        本文标题:Iterator and Spliterator

        本文链接:https://www.haomeiwen.com/subject/cijdsqtx.html