What is the Iterable interface used for?

一笑奈何 提交于 2019-11-28 05:44:21

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) {
    ...
}

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.

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.

The Iterable Javadoc gives a full list of classes that implement Iterable.

If you have a complicated data set, like a tree or a helical queue (yes, I just made that up), but you don't care how it's structured internally, you just want to get all elements one by one, you get it to return an iterator.

The complex object in question, be it a tree or a queue or a WombleBasket implements Iterable, and can return an iterator object that you can query using the Iterator methods.

That way, you can just ask it if it hasNext(), and if it does, you get the next() item, without worrying where to get it from the tree or wherever.

It returns an java.util.Iterator. It is mainly used to be able to use the implementing type in the enhanced for loop

List<Item> list = ...
for (Item i:list) {
 // use i
}

Under the hood the compiler calls the list.iterator() and iterates it giving you the i inside the for loop.

An interface is at its heart a list of methods that a class should implement. The iterable interface is very simple -- there is only one method to implement: Iterator(). When a class implements the Iterable interface, it is telling other classes that you can get an Iterator object to use to iterate over (i.e., traverse) the data in the object.

Iterators basically allow for iteration over any Collection.

It's also what is required to use Java's for-each control statement.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!