CPSC 210

D8: Advanced Iterators

Learning Goals

  • To apply the Iterator Design Pattern to a given problem
    • in the case where you need to design your own iterator class.

The Iterator Pattern

  • Your class needs to implement Iterable<E>
  • Your class returns a home-made iterator when iterator() is called
  • Your iterator...
    • ...must implement Iterator<E>
    • ...must have a counter that keeps track where it is
    • ...must implement hasNext() and next()

Your own iterator

Iterator Hierarchy

Iterable<E>

Iterator<E> iterator()

<<interface>>

Iterator<E>

boolean hasNext()
E next()
void remove()

<<interface>>

returns new MyCollectionIterator<E>()

MyCollection<E>

Iterator<E> iterator()

MyCollectionIterator<E>

Lecture Lab

Toys & Odd Numbers

D8: Advanced Iterators

The End - Thank You!

CPSC210 - D8: Advanced Iterators

By Felix Grund

CPSC210 - D8: Advanced Iterators

  • 875