What is iterable<T> interface in java? (and also iterator)
So the first thing that I wanted to know actually, is why do you need Iterable<T> interface when you have Interface Iterator<T>? Well, here are the descriptions of Iterable and Iterator. I took them from Java Official APIs.
Interface Iterable<T>
Interface Iterator<T>
Ok. Well, the member methods are different. But what is the exact role of each of them?
Iterable
The Collection<E> interface actually extends Interable<E> Interface. And Iterable Interface allows enhanced for-loop by returning Iterator<T> (by using the method iterator()). For example:
Code Editor
You can directly use: for(TypeName tempVarName : CollectionName) syntax to iterate over a collection; you don't need to do what is shown on the right side ( creating iterator yourself and doing next() and hasNext() ). The compiler handles it for you.
|
Iterator
Basically, this class helps iterating over a collection. You can access or remove elements in a collection by using iterator. Here's a good example that I got from beginnersbook.com:
|
Summary
Yeah. again, I think I got a good answer from stackoverflow.com:
Yeah. again, I think I got a good answer from stackoverflow.com:
An Iterable is a simple representation of a series of elements that can be iterated over.
It does not have any iteration state such as a "current element".
Instead, it has one method that produces an Iterator.
An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext().
and move to the next element (if any) using next().Typically, an Iterable should be able to produce any number of valid Iterators.