Iterators let you process each element of a
Collection. Iterators are a
nice vanilla, generic way to go through all the elements of a Collection no matter how it is organised. Iterator is an
Interface implemented a different way for every
Collection. Iterator has
replaced the older Enumeration interface.
Iterable is the interface that notes the class has
a iterator method capable of emitting a one-shot
Iterator object. Since Iterable in a superinterface of Collection, all Collections are
Iterable, but not the reverse. The for:each shorthand loop syntax works only on classes that implement
Iterable.
Sample Code
Note how Iterators deliver raw Objects with the
next method. It is up to you to cast them back to what
they really are.
Generics
With generics, Iterators are typed and hence you don’t need the cast to
fish each object out of them. Further, you have access to the for:each loop.
Implementing
Here is how a simple Iterator works inside:
Here is how a more realistic one works that implements ListIterator.
Iterators optionally implement the remove method or just leave a dummy stub that triggers an exception.
Remove
While in the middle of using an Iterator, if you try to add or remove elements, with Collection methods, you will get a ConcurrentModificationException. You can add and remove elements if
you use Iterator. remove
or ListIterator. add. The
alternative is to create a todo Collection during the iteration pass and
then add or delete the elements when you are done.
Deleting a large number of elements from a large ArrayList will run faster if you create a new ArrayList just the right size, then populate it leaving out the
undesirable elements. This avoids the repeated sliding down of all elements above the
deleted one. Also processing an ArrayList in descending
order to delete is more efficient since remove will not
need to slide elements that will be soon deleted.
The wonderful thing about Iterator is whether you iterate over the original
Collection, a keySet, valuesor an entrySet
it still removes the item from the original Collection.
Here is some sampe code to use Iterator.remove.
Iterable
You might want to make your own class implement Iterable, so that you can
use it in a for:each statement.
Learning More
Oracle’s Javadoc on
Iterator interface : available:
Oracle’s Javadoc on
ListIterator interface : available:
Oracle’s Javadoc on
Iterable interface : available:
Oracle’s Javadoc on
Enumeration interface : available: