Iterator
There is a powerful and consistent way to traverse almost all data structures in Java including lists - Iterator.
The two important methods belonging to Iterator
interface are:
hasNext()
: returnstrue
if there is an item in front of the current position of the iterator.next()
: returns the item in front of the current position of the iterator (if any), and moves the iterator forward. ThrowsNoSuchElementException
if the iteration has no more elements.
A class that implements Iterator
interface can add other methods too. ListIterator is one such class.
We will focus only on
hasNext()
andnext()
.
The advantages of using an iterator are,
- It’s consistent across any class that implements the
Iterator
interface. - It’s intuitive as in “while the collection has another item, access it”.
Creating and using a ListIterator on a List object
A ListIterator iter
is created on a List object list
as:
1
ListIterator<Integer> iter = list.listIterator();
Assuming the list is [10, 70, 20, 90, 30, 80], the initial state of iter
is represented by the red block.
You can check if there is an item in front of the current position of the iterator as:
1
boolean itemExists = iter.hasNext();
Once you check an item exists, you can access it as:
1
Object item = iter.next();
This (accessing an item) results in the iterator moving forward by one.
Complete example
1
2
3
4
5
6
ArrayList<Integer> list = new ArrayList(Arrays.asList(10, 70, 20, 90, 30, 80));
ListIterator<Integer> iter = list.listIterator();
while(iter.hasNext()) {
System.out.print(iter.next()+" ");
}
//displays 10 70 20 90 80 30
Initial state
After first iteration
After second iteration
After third iteration
After fourth iteration
After fifth iteration
After sixth iteration