GeeksforGeeks articles

Iterator and Spliterator

2019-02-02  本文已影响0人  gattonero

Iterator

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

//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.iterator();
iterator.hasNext();//boolean
iterator.next();//Object
iterator.remove()//void

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

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

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/

上一篇下一篇

猜你喜欢

热点阅读