What is the difference between iterator and iterable and how to use them?

Charles Cai picture Charles Cai · Jul 28, 2011 · Viewed 133.2k times · Source

I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?

Answer

ColinD picture ColinD · Jul 28, 2011

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.