@xtccc
2015-11-24T14:15:00.000000Z
字数 956
阅读 2413
Scala
简而言之,Iterator
有状态,而Iterable
无状态。看看API doc是怎么说的。
Iterable :
A base trait for iterable collections.
This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements. [...] This trait implements Iterable's
foreach
method by stepping through all elements using iterator.
Iteraotor :
Iterators are data structures that allow to iterate over a sequence of elements. They have a
hasNext
method for checking if there is a next element available, and anext
method which returns the next element and discards it from the iterator.An iterator is mutable: most operations on it change its state. While it is often used to iterate through the elements of a collection, it can also be used without being backed by any collection (see constructors on the companion object).
使用一个Iterator
实例:可以迭代到某一处时停下来,然后随后继续迭代下去。
使用一个Iterable
实例:如果迭代到某一处停下来,随后想继续迭代时就不可能了,只能从头开始迭代。
此外,Iterator
扩展了 TraversableOnce
,而Iterable
没有。
由于Iterator有状态的,因此在使用时可能会隐藏着地雷,请参考 Iterators in Scala: glory and danger .