CPSC 210
D8: Advanced Iterators
Applying Iterators
for (Item next : collection) {
// do something with next
}
- What collection do you want to iterate over? That is your Iterable.
- What type of data do you want to iterate over? That identifies the type parameter for the Iterable<Item> and Iterator<Item>
- Provide an implementation for the iterator() method.
Modification while Iterating
2
6
-1
8
-5
4
2
6
-1
8
-5
4
2
6
-1
8
-5
4
2
6
-1
8
-5
4
2
6
8
4
...
...
...
...
...
2
6
8
4
...
Not Good! 8 is skipped
Expected behaviour
Remove Negative Numbers
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
Image source: https://refactoring.guru/
- 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!
D8: Advanced Iterators
By firas_moosvi
D8: Advanced Iterators
- 55