COMP2511
Iterator Pattern
Prepared by
Dr. Ashesh Mahidadia
Iterator Pattern: Intent and Motivation
v The intent of the Iterator design pattern is to:
“Provide a way to access the elements of an aggregate object sequentially without
exposing its underlying representation.” [GoF]
v Exposing representation details of an aggregate breaks its encapsulation.
v Problem to address:
How can the elements of an aggregate object be accessed and traversed without
exposing its underlying representation?
v “But you probably don’t want to bloat the List [Aggregate] interface with operations for
different traversals, even if you could anticipate the ones you will need.” [GoF, p257]
COMP2511: Generics, Collections, Iterator 2
Iterator Pattern: Possible Solution
v Encapsulate the access and traversal of an
aggregate in a separate Iterator object.
v Clients request an Iterator object from an
aggregate (say by calling createIterator()) and use
it to access and traverse the aggregate.
v Define an interface for accessing and traversing the
elements of an aggregate object
(next(), hasNext()).
v Define classes (Iterator1,…) that implement the
Iterator interface.
COMP2511: Generics, Collections, Iterator 3
Iterator Pattern: Possible Solution
v An iterator is usually implemented as inner class of an aggregate class. This enables the
iterator to access the internal data structures of the aggregate.
v New access and traversal operations can be added by defining new iterators.
For example, traversing back-to-front: previous(), hasPrevious().
v An aggregate provides an interface for creating an iterator (createIterator()).
v Clients can use different Iterator objects to access and traverse an aggregate object in
different ways.
v Multiple traversals can be in progress on the same aggregate object (simultaneous
traversals). However, need to consider concurrent usage issues!
COMP2511: Generics, Collections, Iterator 4
Iterator Pattern: Java Collection Framework
The Java Collections Framework provides,
v a general purpose iterator
next(), hasNext(), remove()
v an extended listIterator
next(), hasNext(), previous(), hasPrevious(), remove(), ….
COMP2511: Generics, Collections, Iterator 5
Example:
Custom Iterator
COMP2511: Generics, Collections, Iterator 6
Using or forwarding an iterator method from
a collection (i.e. Hashtable, ArrayList, etc.)
Implement Iterator interface, and provide the
required methods (and more if required).
Read the
example c
ode
discussed
/develope
d in the
lectures,
and also p
rovided
for this we
ek
Demo: Iterator Pattern
Demo …
COMP2511: Generics, Collections, Iterator 7
End
COMP2511: Generics, Collections, Iterator 8