Iterator Example in Java
Problem
An Iterator gives explicit, step-by-step access to a collection's elements through hasNext() and next(), and is the only safe way to remove elements while a loop over the collection is still in progress.
Given a list of numbers, remove every one divisible by 15 while iterating, using an Iterator instead of a for-each loop.
Java Program
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorDemo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(15);
numbers.add(20);
numbers.add(25);
numbers.add(30);
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
int value = it.next();
if (value % 15 == 0) {
it.remove(); // safe removal during iteration — uses the iterator, not the list
}
}
System.out.println(numbers);
}
}Output
Core Logic
Walking the list with an explicit Iterator, instead of a for-each loop, is what allows calling remove() safely mid-traversal without disturbing the iteration itself.
- 1
numbers.iterator()returns anIterator<Integer>positioned before the first element. - 2
hasNext()checks whether another element remains, andnext()advances to it and returns its value. - 3
it.remove()deletes the elementnext()just returned — this is the iterator's own remove method, not the list's. - 4The loop continues correctly after each removal, since the iterator tracks its own position internally as elements shift.
[10, 15, 20, 25, 30], both 15 and 30 are divisible by 15 and get removed, leaving [10, 20, 25].Key Point: Calling numbers.remove(...) directly on the list instead of on the iterator would corrupt the iteration and throw an exception — this exact failure is what the dedicated Fail-Fast Iterator page demonstrates.
Why: The iterator visits each of the n elements once; on an ArrayList, each remove() call also shifts every later element down by one, so removing many elements can push the total work toward O(n²), though a single pass with only a few removals stays close to O(n).