What is the difference between Iterator and ListIterator in Java?
Iterator is the general-purpose interface. It has exactly three methods — hasNext, next and remove — and it gives you forward-only traversal over any Collection. The remove method deletes the element the iterator last returned, and it is the only way to remove during traversal without triggering the fail-fast check.
ListIterator extends Iterator and is obtained from a List rather than from the Collection interface. It adds four things. It allows bidirectional traversal, with previous and hasPrevious. It exposes the index of the current position, through nextIndex and And it adds an add method that inserts a new element at the current position.previousIndex. It adds a set method that replaces the element the iterator last returned.
That gives ListIterator a genuinely useful property: it can insert into the list at the cursor without shifting the remaining elements the way the List's own add(int, E) would. For an ArrayList, inserting through the iterator is O(n) because the array still has to shift, but for a LinkedList it is O(1), because the node is simply relinked.
One subtlety worth knowing. The remove and set methods may only be called after a next or previous call, because they act on the element the iterator last returned. Calling them first throws IllegalStateException.
And a reminder about the fail-fast behaviour: both iterators detect concurrent modification and throw ConcurrentModificationException, but only if the collection supports it. The iterator of a ConcurrentHashMap, for instance, is weakly consistent and never throws.