Quick Index
Videos


A quick video on this chapter is here....

Overview


Iterators require just a little bit of coding.

The key is spending a little time up front understanding their concept and mechanism (before jumping into the code).

Iterator Concepts


What and Why?


What?
An iterator is a simple object that visits all elements in a structure.

Think spider walking along elements.
Why?
Simplicity.

Iterators are super user-friendly.


ADT


Here is the iterator ADT:

Method NameDescriptionException Case
nextReturn next data element and move to nextIf at end, throw runtime exception "no more elements"
hasNextIf NOT at end, return true, else falseNone

Notes:

Examples


Here is an example (algorithm) where we print all the elements in the structure using an iterator.

Iterate Over an Arrayed List
This little algorithm has us visiting the entire list.
iterator = myArrayedList.toIterator()
While iterator.hasNext()
	print(iterator.next());
Iterate Over a Linked List
This little algorithm has us visiting the entire list.
iterator = myLinkedList.toIterator()
While iterator.hasNext()
	print(iterator.next());
Iterate Over a Complex Tree
This little algorithm has us visiting the complex tree.
iterator = myComplexTree.toIterator()
While iterator.hasNext()
	print(iterator.next());
Beautifully Simple Pattern
You get the idea -- using an iterator is always the same.
While iterator.hasNext()
	print(iterator.next());
BTW - Output

Given this input:
	list = [10, 20, 30, 40]
The expected output is shown
10
20
30
40


References



Requirements


The iterator class for a dynamic array must implement the provided StructureIterator ADT (Java interface)

Iterator Design