[关闭]
@xtccc 2015-11-24T14:15:00.000000Z 字数 956 阅读 2413

Iterable & Iterator

给我写信
GitHub

此处输入图片的描述

Scala




Iterable与Iterator的区别


简而言之,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 a next 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 的潜在危险


由于Iterator有状态的,因此在使用时可能会隐藏着地雷,请参考 Iterators in Scala: glory and danger .

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注