In the language of Java, a collection is just a set of objects. A collection may or may not have order depending on how the collection class is implemented. Examples collection are
Set (unordered), and
A collection iterator is an object that takes a collection and provide the methods to go through the elements of the collection, one at a time. For example, the following code contains a
c, and an iterator,
itr, that prints out each element.
Every collection iterator must implement
Iterator<E> interface. This interface only defines 3 methods (behaviors) that all iterators have:
hasNext(): this method tells the user of the iterator if the collection has more elements to go through.
next(): if hasNext() returns true, this method gets the next element and advance the internal tracker.
remove(): this is rarely implemented; usually the body of this is left blank or throws UnsupportedOperationException.
Iterator<E> is a generic interface. This simply mean that it can be an iterator of different types; or the collection is generic.
From the code above, we see that we can get an iterator for a collection by calling the
iterator() method on the collection object. The next question, how do we implement an iterator for our own collection?
An iterator is usually implemented by the the author of the collection, and it really is just a class that implements the
Iterator<E> interface. With that said, iterators are often written as an inner class of the collection class, so that the iterator can have access the internals of the collection. The following code shows a simple collection class using array and an iterator as inner class.
The following is the breakdown:
- Line 9-21 is the iterator class, which has required methods:
next()line 19, and
iterator()method (line 4), which returns an instance of our iterator class.
Iterator Shortcut (For-Each Loop)
We don’t have to explicitly call the
iterator() method to get the iterator from a collection. Java’s for-each loop will do all these for us implicitly. The following code does the same as the first code snippet.
This is called for-each loop. And what it does is for each element in collection
c, the loop runs one time. Each time, the element is assigned to