Tracing the ArraySet Iterator
We built the ArraySetIterator. Now let’s run it on an example. Take a mailing list that holds three email addresses. We draw only the first four slots of the backing array. The iterator starts with cursor at 0. hasNext() checks cursor < size, which is 0 < 3:
size
↓
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ ann@jhu.edu │ bob@jhu.edu │ cy@jhu.edu │ _ │
└─────────────┴─────────────┴─────────────┴─────────────┘
↑
cursor
next() returns arr[cursor], which is ann@jhu.edu, and moves cursor to 1:
size
↓
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ ann@jhu.edu │ bob@jhu.edu │ cy@jhu.edu │ _ │
└─────────────┴─────────────┴─────────────┴─────────────┘
↑
cursor
The next call returns bob@jhu.edu and moves cursor to 2:
size
↓
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ ann@jhu.edu │ bob@jhu.edu │ cy@jhu.edu │ _ │
└─────────────┴─────────────┴─────────────┴─────────────┘
↑
cursor
One more call returns cy@jhu.edu and moves cursor to 3:
size
↓
┌─────────────┬─────────────┬─────────────┬─────────────┐
│ ann@jhu.edu │ bob@jhu.edu │ cy@jhu.edu │ _ │
└─────────────┴─────────────┴─────────────┴─────────────┘
↑
cursor
Now hasNext() checks 3 < 3, which is false, so the iteration stops. The iterator never returns the empty slot at index 3.
The enhanced for loop works the same as before. The difference is that now we decide which element comes next and when the iteration stops. If we wanted to return the elements in reverse order, or visit every other one, we would change only hasNext() and next().