What is the difference between iterator and iterable and how to use them?
Solution 1:
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 Iterator
s.
Solution 2:
An implementation of Iterable
is one that provides an Iterator
of itself:
public interface Iterable<T>
{
Iterator<T> iterator();
}
An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).
public interface Iterator<E>
{
boolean hasNext();
E next();
void remove();
}
See Javadoc.
Solution 3:
I will answer the question especially about ArrayList as an example in order to help you understand better..
- Iterable interface forces its subclasses to implement abstract method 'iterator()'.
public interface Iterable { ... abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T. ... }
- Iterator interface forces its subclasses to implement abstract method 'hasNext()' and 'next()'.
public interface Iterator { ... abstract boolean hasNext(); //Returns true if the iteration has more elements. abstract E next(); //Returns the next element in the iteration. ... }
- ArrayList implements List, List extends Collection and Collection extends Iterable..
That is, you could see the relationship like
'Iterable <- Collection <- List <- ArrayList'
. And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.
- I am going to show ArrayList source code with 'iterator()' method as follows for more detailed information.
'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.
public class ArrayList<E> ... implements List<E>, ... { ... public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { ... public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } ... } }
- Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).
Here is a simple example.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string);
}
}
Now, is it clear? :)
Solution 4:
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
Solution 5:
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.