I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?
I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?
I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:
Think of a public library. Old school. With paper books. Yes, that kind of library.
A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.
The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".
I know it's a bit silly, but I hope this helps.
As explained here, The āIterableā was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
Iterable were introduced to use in for each loop in java
public interface Collection<E> extends Iterable<E>
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
An anonymous class easily converts an Iterator to an Iterable and lets you use the Iterable syntax (for loops, forEach()).
Example: consider an Iterator<T> it
for (T element : new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
}) {
//do something with `T element`
}
Abstracted in a function
static <T> Iterable<T> toIterable(Iterator<T> it) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return it;
}
};
}
Usage
for (T element: toIterable(it) {
...
}