ListIterator for…well, iterating lists, of course
When programming, it’s easy to mindlessly reach for the same tool repeatedly. The tool is well known and has worked in the past. Ole reliable. But there comes a time when looking beyond the familiar in favor of something more effective can pay big dividends. Maybe something that’s been overlooked simply out of habit.
Until recently, I used an Iterator to traverse Lists. But when a requirement to traverse a list backwards crossed my desk, I (finally) went looking for something better. I suppose it took a new requirement for me to open my eyes wider because right there, in the same package, is ListIterator. A ListIterator allows you to:
- traverse a list in either direction
- modify the list during iteration
- obtain the iterator’s current position in the list
IMO, the best feature of ListIterator is modifying the list during iteration. For example:
ListIterator<BizItem> iter = mylist.listIterator();
while (iter.hasNext()) {
BizItem next = iter.next();
if (next.isTooOld()) {
iter.remove();
// or iter.set(new BizItem());
}
}