Iterators
Using for
loops on lists can be dangerous as their size is not static.
We can separate the traversal logic from the underlying collection by using iterators.
Iterator Design Pattern
Iterators provide a way to access elements of an aggregate object sequentially without exposing its underling representation.
- Iterators are objects.
- Single-use
- Represents one complete iteration across the collection.
- Can provide safe access to a collection.
- Are often created by the collection itself.
Example
We can filer a List<Bill>
using an Iterator
as follows:
// get an iterator from the collection
Iterator<Bill> iter = bills.iterator();
while (iter.hasNext()){
Bill b = iter.next(); // access next entry
if (b.is_paid()){
iter.remove(); // remove it from the list
}
}
Java Iterators
Iterator<T>
is a parameterised interface. You must specify the type of object stored in the collection.Iterators
provide a saferemove()
method that removes the last element returned by itsnext()
method.- This is different from the
remove()
method of the collection.
Alternative for
Syntax
If you don’t need to write to the collection, so don’t need the iterator, then you can use the following syntax:
for (Bill b : bills){
// System.out.println(b);
}
which is equivalent to:
Iterator<Bill> iter=bills.iterator();
while (iter.hasNext()){
Bill b = iter.next();
// System.out.println(b);
}