List Iterators
LinkedList list = . . .;
ListIterator iterator = list.listIterator();
while (iterator.hasNext())
{
Object current = iterator.next();
. . .
}
Classical List Data Structure
High-Level View of Data Structures
- Queue
- Array with random access
- List
???
List with Cursor
for (list.reset(); list.hasNext(); list.next())
{
Object x = list.get();
. . .
}
- Disadvantage: Only one cursor per list
- Iterator is superior concept
The Pattern Concept
- History: Architectural Patterns
- Christopher Alexander
- Each pattern has
- a short name
- a brief description of the context
- a lengthy description of the problem
- a prescription for the solution
Short Passages Pattern
Short Passages Pattern
Context
"...Long, sterile corridors set the scene for everything bad about
modern architecture..."
Problem
a lengthy description of the problem, including
- a depressing picture
- issues of light and furniture
- research about patient anxiety in hospitals
- research that suggests that corridors over 50 ft are considered
uncomfortable
Short Passages Pattern
Solution
Keep passages short. Make them as much like rooms as possible, with
carpets or wood on the floor, furniture, bookshelves, beautiful
windows. Make them generous in shape and always give them plenty of
light; the best corridors and passages of all are those which have
windows along an entire wall.
Iterator Pattern
Context
- An aggregate object contains element objects
- Clients need access to the element objects
- The aggregate object should not expose its internal structure
- Multiple clients may want independent access
Iterator Pattern
Solution
- Define an iterator that fetches one element at a time
- Each iterator object keeps track of the position of the next
element
- If there are several aggregate/iterator variations, it is best if
the aggregate and iterator classes realize common interface types.
Iterator Pattern
Iterator Pattern
- Names in pattern are examples
- Names differ in each occurrence of pattern
Name in
Design Pattern
|
Actual Name
(linked lists)
|
Aggregate
|
List
|
ConcreteAggregate
|
LinkedList
|
Iterator
|
ListIterator
|
ConcreteIterator
|
anonymous class implementing ListIterator
|
createIterator()
|
listIterator()
|
next()
|
next()
|
isDone()
|
opposite of hasNext()
|
currentItem()
|
return value of hasNext()
|
Maintained by John Loomis,
last updated 25 February 2007