A helpful trick for designing objects is to do an scratch simulation (scratch sim), scratched with pencil onto paper.

To implement an iterator, it takes very little coding. However, they can be tricky to design. Perfect candidates for scratch sim.

Simple Algorithm


Example #1 - Printing Objects
//Iterating over any object type
while iterator.hasNext()
	print(iterator.next());
Example #2 - Summing
//Iterating over numbers
Sum = 0
while iterator.hasNext()
	sum = sum + iterator.next();
Just Two Methods
Our entire communication with iterator is just using "hasNext" and "next".
While iterator.hasNext()
	doAnything(iterator.next());


Simulation


For an algorithm that looks so simple, it can be a head scratcher determining how to start. Who are the players (ivars)? How are parts are moving?

Time for scratch sim.

A Simulation Run
We start off simulating an iterator walking a short list.
Given this input: [10, 20, 30, 40]
The expected output is shown
10
20
30
40
Scratch Simulation
To produce the output, we need to send "get" multiple times.

We scratch them on our sketch.
10	get(0)
20	get(1)
30	get(2)
40	get(3)
Ivar Harvest 1
We see we need to send "get" to a DynamicArray. We'll call it "array".

Our first ivar of the design: "array"
Scratch Simulation (Revisited)
Now we see we have an index that is increasing: 0, 1, 2, 3
10	get(0)
20	get(1)
30	get(2)
40	get(3)
Ivar Harvest 2
Bingo, our next ivar: "nextIndex"


Design Pieces


Key Pieces


NameTypeDescription
DynArrayIteratorClassThe class to code
arrayDynamicArrayivar that we send "get" to
nextIndexintivar that we use for "get"
and that we increment


Key Actions



Simple Test Code


It's super helpful to have even one simple test ready to go before we start coding. Below is an example.

Simple Test
Here we walk the iterator from start to end and make sure "next" answers 10, 20, 30, 40.
list = [10, 20, 30, 40]
iter = new Iterator(list)
index = 0
while (iter.hasNext())
	Test that iter.next() equals list[index]
	index++


Ready to Code


Now we're ready to code. Rather than just sitting down at the keyboard and trying to figure out this interesting object called an "iterator", we now have a plan.