Java Iterator and ListIterator – Complete Guide with Examples
Learn how to traverse Java collections using Iterator and ListIterator, their differences, methods, and practical examples for List, Set, and Map traversal.
Iterator and ListIterator in Java – Complete Detailed Tutorial
In Java, collections can be traversed using Iterator and ListIterator. They provide a standard way to iterate over elements without exposing the underlying structure.
1. Iterator Interface
- Iterator is used to traverse any Collection (List, Set, etc.)
- Supports forward-only traversal
- Allows removal of elements during iteration
- Part of java.util package
Common Methods:
| MethodDescription | |
| hasNext() | Checks if next element exists |
| next() | Returns next element |
| remove() | Removes current element |
Example – Using Iterator with ArrayList
Output:
Key Points:
- Can traverse List, Set, or any Collection
- Supports element removal but not modification
2. ListIterator Interface
- ListIterator is a bidirectional iterator for List implementations (ArrayList, LinkedList)
- Supports forward and backward traversal
- Can add, remove, or modify elements during iteration
Common Methods:
| MethodDescription | |
| hasNext() | Checks if next element exists |
| next() | Returns next element |
| hasPrevious() | Checks if previous element exists |
| previous() | Returns previous element |
| add(E e) | Adds element at current position |
| set(E e) | Replaces last returned element |
| remove() | Removes last returned element |
Example – Using ListIterator with LinkedList
Output:
Key Points:
- Works only with List implementations
- Allows bidirectional traversal
- Supports modification, addition, and removal
3. Iterator vs ListIterator
| FeatureIteratorListIterator | ||
| Traversal | Forward only | Forward and backward |
| Collection type | All Collections | Only List |
| Modify | Can remove only | Can add, remove, replace |
| Position control | No | Yes (nextIndex, previousIndex) |
4. Key Points
- Iterator: simple forward traversal, removal allowed
- ListIterator: advanced, bidirectional, can modify elements
- Both avoid exposing underlying collection structure
5. Summary
- Iterator and ListIterator are core for safe collection traversal
- Choose Iterator for generic traversal
- Choose ListIterator for Lists needing bidirectional traversal or modification
- Always use iterator methods instead of modifying collection directly