Johanna
Johanna

Reputation: 27628

What is the Iterable interface used for?

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

Upvotes: 41

Views: 48596

Answers (6)

Kaumadie Kariyawasam
Kaumadie Kariyawasam

Reputation: 1456

The Iterable is defined as a generic type.

Iterable , where T type parameter represents the type of elements returned by the iterator.

An object that implements this interface allows it to be the target of the “foreach” statement. The for-each loop is used for iterating over arrays, collections.

read more -: https://examples.javacodegeeks.com/iterable-java-example-java-lang-iterable-interface/

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 191875

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.

Upvotes: 49

Matt Bridges
Matt Bridges

Reputation: 49385

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.

Upvotes: 4

Peter Kofler
Peter Kofler

Reputation: 9440

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.

Upvotes: 5

Zack Marrapese
Zack Marrapese

Reputation: 12080

Iterators basically allow for iteration over any Collection.

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

Upvotes: 3

Jeremy Smyth
Jeremy Smyth

Reputation: 23493

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.

Upvotes: 14

Related Questions