Iterator : Java Glossary
home I words local find no local find frame, full screen Google search web for topic jump to footer translate with Babelfish 2006-03-08 by Roedy Green ©1996-2008 Canadian Mind Products
Go to : punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all)
Iterator
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.

Sample Code Remove
Generics Learning More
Implementing Links

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.

Learning More

Sun’s Javadoc on the Iterator class : available:
Sun’s Javadoc on the ListIterator class : available:
Sun’s Javadoc on the Iterable class : available:
Sun’s Javadoc on the Enumeration class : available:

CMP_homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.18] The information on this page is for non-military use only.
You are visitor number 44,596. Military use includes use by defence contractors.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/Mindprod website mirror)
http://mindprod.com/jgloss/iterator.html J:\mindprod\jgloss\iterator.html