问题描述
我是初学者,我无法理解 Iterable
界面的实际效果。
I am a beginner and I cannot understand the real effect of the Iterable
interface.
推荐答案
除了杰里米所说的,它的主要好处是它有一些语法糖:。如果你有一个 Iterable< String>
,你可以这样做:
Besides what Jeremy said, its main benefit is that it has its own bit of syntactic sugar: the enhanced for-loop. If you have, say, an Iterable<String>
, you can do:
for (String str : myIterable) {
...
}
Iterator< String> 的所有脏工作,检查它是否 hasNext()
,并调用 str = getNext()
由编译器在幕后处理。
Nice and easy, isn't it? All the dirty work of creating the Iterator<String>
, checking if it hasNext()
, and calling str = getNext()
is handled behind the scenes by the compiler.
由于大多数集合都实现了 Iterable
或者有一个返回一个的视图(例如 Map
's keySet()
或 values()
),这使得处理集合变得更加容易。
And since most collections either implement Iterable
or have a view that returns one (such as Map
's keySet()
or values()
), this makes working with collections much easier.
给出了实现 Iterable
的类的完整列表。
The Iterable
Javadoc gives a full list of classes that implement Iterable
.
这篇关于什么是Iterable接口用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!