An iterator over a collection.
Iterator takes the place of Enumeration in the Java collections framework.
Iterators differ from enumerations in two ways:
1. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
2. Method names have been improved.
public interface ListIterator<E> extends Iterator<E>
An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.
A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().
An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:
Element(0) Element(1) Element(2) ... Element(n-1
cursor positions:^ ^ ^ ^ ^
Note that the remove and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next or previous().
Key points about Iterator:
Ø Iterator in Java support generics so always use Generic version of Iterator rather than using Iterator with raw type.
Ø If you want to remove objects from Collection than don't use for-each loop instead use Iterator's remove () method to avoid any ConcurrentModificationException.
Ø Iterating over collection using Iterator is subject to ConcurrentModificationExc if Collection is modified after Iteration started, but this only happens in case of fail-fast Iterators.
Ø There are two types of Iterators in Java, fail-fast (ArrayList, HashMap) and fail-safe (CopyOnWriteList, ConcurrentHashMap).
Ø List collection type also supports ListIterator which has add() method to add elements in collection while Iterating.