tags:

views:

240

answers:

5

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

+3  A: 

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.

Jeremy Smyth
+9  A: 

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.

Edit: And here's a link to the Javadocs. All it says is:

Implementing this interface allows an object to be the target of the "foreach" statement.

There's a nice long list of classes that implement Iterable, too.

Michael Myers
+1  A: 

Iterators basically allow for iteration over any Collection.

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

Zack
+1  A: 

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.

Peter Kofler
ahhh - too slow ;-)
Peter Kofler
So far the best answer, though.
Michael Borgwardt
+1  A: 

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.

Matt Bridges