Implement the Iterator Pattern
Part I
We are going to implement our iterator for ArrayIndexedList (instead of using the Arrays.stream(data).iterator).
-
Add a new class
ArrayIndexedListIterator:public class ArrayIndexedListIterator<T> { } -
ArrayIndexedListIteratormust implement theIteratorinterface:public class ArrayIndexedListIterator<T> implements Iterator<T> { } -
The following operations from the
Iteratorinterface are inherited (and need to be implemented):public class ArrayIndexedListIterator<T> implements Iterator<T> { @Override public boolean hasNext() { return false; } @Override public T next() { return null; } }
Let us understand these methods first!
When we use the enhanced for loop, we are using syntactic sugar:
Iterator<MyType> it = myCollection.iterator();
while (it.hasNext()) {
MyType element = it.next();
// do something with element
}
// the loop above is the same as the one below
for(MyType element : myCollection) {
// do something with element
}
From the while loop, it is clear the next method returns the next element in the iteration. And, hasNext returns true if the iteration has more elements.