Question

I am a beginner and I cannot understand the real effect of the Iterable interface.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top