問題描述
提供無限"的 Iterator
實現通常被認為是不好的做法嗎?即對 hasNext()
always(*) 的調用在哪里返回 true?
Is it generally considered bad practice to provide Iterator
implementations that are "infinite"; i.e. where calls to hasNext()
always(*) return true?
通常我會說是",因為調用代碼可能會出現異常行為,但在下面的實現中,hasNext()
將返回 true,除非調用者從列表中刪除迭代器所在的所有元素初始化為;即有一個終止條件.你認為這是對 Iterator
的合法使用嗎?盡管我想有人可能會說它不直觀,但它似乎并沒有違反合同.
Typically I'd say "yes" because the calling code could behave erratically, but in the below implementation hasNext()
will return true unless the caller removes all elements from the List that the iterator was initialised with; i.e. there is a termination condition. Do you think this is a legitimate use of Iterator
? It doesn't seem to violate the contract although I suppose one could argue it's unintuitive.
public class CyclicIterator<T> implements Iterator<T> {
private final List<T> l;
private Iterator<T> it;
public CyclicIterator<T>(List<T> l) {
this.l = l;
this.it = l.iterator();
}
public boolean hasNext() {
return !l.isEmpty();
}
public T next() {
T ret;
if (!hasNext()) {
throw new NoSuchElementException();
} else if (it.hasNext()) {
ret = it.next();
} else {
it = l.iterator();
ret = it.next();
}
return ret;
}
public void remove() {
it.remove();
}
}
(迂腐)編輯
有些人評論了如何使用 Iterator
從無界序列(如斐波那契序列)生成值.但是,Java Iterator
文檔指出 Iterator 是:
Some people have commented how an Iterator
could be used to generate values from an unbounded sequence such as the Fibonacci sequence. However, the Java Iterator
documentation states that an Iterator is:
集合上的迭代器.
現在你可以說斐波那契數列是一個無限集合,但在 Java 中我會將集合等同于 java.util.Collection
接口,它提供了諸如 size()
暗示一個集合必須是有界的.因此,使用 Iterator
作為無界序列的值生成器是否合法?
Now you could argue that the Fibonacci sequence is an infinite collection but in Java I would equate collection with the java.util.Collection
interface, which offers methods such as size()
implying that a collection must be bounded. Therefore, is it legitimate to use Iterator
as a generator of values from an unbounded sequence?
推薦答案
我認為它完全合法 - Iterator
只是一個東西"流.為什么流必須有界?
I think it is entirely legitimate - an Iterator
is just a stream of "stuff". Why should the stream necessarily be bounded?
許多其他語言(例如 Scala)都內置了無限流的概念,并且可以對其進行迭代.例如,使用 scalaz
Plenty of other languages (e.g. Scala) have the concept of unbounded streams built in to them and these can be iterated over. For example, using scalaz
scala> val fibs = (0, 1).iterate[Stream](t2 => t2._2 -> (t2._1 + t2._2)).map(_._1).iterator
fibs: Iterator[Int] = non-empty iterator
scala> fibs.take(10).mkString(", ") //first 10 fibonnacci numbers
res0: String = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
就最小意外原則而言,我認為這完全取決于上下文.例如,我希望這個方法返回什么?
public Iterator<Integer> fibonacciSequence();
這篇關于是一個“無限"的迭代器設計不好?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!