【发布时间】:2015-05-16 05:20:18
【问题描述】:
我注意到以下场景中的一些奇怪行为:
迭代器 -> 流 -> map() -> 迭代器() -> 迭代
原始迭代器的 hasNext() 在已经返回 false 后被再次调用。
这正常吗?
package com.test.iterators;
import java.util.Iterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class TestIterator {
private static int counter = 2;
public static void main(String[] args) {
class AdapterIterator implements Iterator<Integer> {
boolean active = true;
@Override
public boolean hasNext() {
System.out.println("hasNext() called");
if (!active) {
System.out.println("Ignoring duplicate call to hasNext!!!!");
return false;
}
boolean hasNext = counter >= 0;
System.out.println("actually has next:" + active);
if (!hasNext) {
active = false;
}
return hasNext;
}
@Override
public Integer next() {
System.out.println("next() called");
return counter--;
}
}
Stream<Integer> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(new AdapterIterator(), 0), false);
stream.map(num -> num + 1).iterator().forEachRemaining(num -> {
System.out.println(num);
});
}
}
如果我删除 map() 或将最终的 itearator() 替换为 count() 或 collect() 之类的东西,它可以在没有冗余调用的情况下工作。
输出
hasNext() called
actually has next:true
next() called
3
hasNext() called
actually has next:true
next() called
2
hasNext() called
actually has next:true
next() called
1
hasNext() called
actually has next:true
hasNext() called
Ignoring duplicate call to hasNext!!!!
【问题讨论】:
-
我不会称之为“正常”,但在规范范围内。
-
你的意思是因为 Iterator.hasNext() 必须是幂等的,对吧?
-
对,
next可以被调用者喜欢的次数...
标签: iterator java-8 java-stream spliterator