简体   繁体   English

Iterator.hasNext应该是副作用吗?

[英]Should Iterator.hasNext be side effect free?

I am writing an iterator that iterates over a list of lists by delegating to the "current" lists own iterator. 我正在编写一个迭代器,它通过委托给“当前”列表自己的迭代器来遍历列表列表。 (No I'm not, but this is a simple example). (不,我不是,但这是一个简单的例子)。 Now, when I reach the end of one list, I need to update the delegate to point to the next lists' iterator. 现在,当我到达一个列表的末尾时,我需要更新委托以指向下一个列表的迭代器。 Can I do this in "hasNext"? 我可以在“hasNext”中执行此操作吗? Or is it better to implement in "next" prior to returning to the caller? 或者在返回呼叫者之前在“下一步”中实施是否更好? I feel "hasNext" should better be side effect free. 我觉得“hasNext”应该更好地免费副作用。 What's your opinion on this? 你对此有何看法?

It would be OK for hasNext to have side effects as long as they are not perceptible from the outside. 只要它们不能从外部感知到hasNext就可以有副作用。 Above all, it must be idempotent . 最重要的是,它必须是幂等的 It is in fact often the case that hasNext can't know whether there is a next without fetching it, and, even if it could "unfetch", it is OK to cache. 实际上通常情况是hasNext无法知道是否有下一个没有获取它,并且,即使它可以“取消”,也可以缓存。

Guava's Iterators.concat does that. Guava的Iterators.concat就是这么做的。 From the javadocs, it: 从javadocs,它:

public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs)

Combines multiple iterators into a single iterator. 将多个迭代器组合到一个迭代器中。 The returned iterator iterates across the elements of each iterator in {@code inputs}. 返回的迭代器遍历{@code inputs}中每个迭代器的元素。 The input iterators are not polled until necessary. 必要时不会轮询输入迭代器。

If you look at the source code you will see that the hasNext method changes the current iterator to the next iterator ie it is not free of side effects, so this approach is ok. 如果查看源代码,您会看到hasNext方法将current迭代器更改为下一个迭代器,即它没有副作用,所以这种方法没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM