Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Iterable interface used for?

Tags:

java

iterable

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

like image 387
Johanna Avatar asked Jun 29 '09 16:06

Johanna


People also ask

What is difference between iterator and iterable interface?

Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.

Is iterable a functional interface?

Iterable isn't a FunctionalInterface so how can it be assigned this lambda?

What does iterable mean in Python?

Iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.

Where is iterator used?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java. util package.


1 Answers

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.

like image 95
Michael Myers Avatar answered Oct 13 '22 03:10

Michael Myers