What is the Iterable interface used for?
Asked Answered
C

6

40

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

Carolann answered 29/6, 2009 at 16:6 Comment(0)
L
49

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.

Lizzielizzy answered 29/6, 2009 at 16:10 Comment(0)
O
14

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.

Olnton answered 29/6, 2009 at 16:9 Comment(0)
O
5

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.

Oppressive answered 29/6, 2009 at 16:11 Comment(1)
So far the best answer, though.Monodrama
C
4

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.

Chaudoin answered 29/6, 2009 at 16:13 Comment(0)
C
3

Iterators basically allow for iteration over any Collection.

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

Cara answered 29/6, 2009 at 16:11 Comment(0)
C
0

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/

Callipygian answered 19/3, 2021 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.