The iterator()
method is a fundamental feature in Java’s ArrayList
class, providing a way to retrieve an Iterator to traverse elements sequentially. Using an iterator is especially useful for safe element access, flexible looping, and performing element removals while iterating.
What Is the iterator() Method in ArrayList?
- The
iterator()
method returns an instance of theIterator
interface for theArrayList
. - This lets you iterate over the elements one by one in proper sequence.
- Iterators provide basic navigation (
hasNext()
,next()
) and safe element removal (remove()
) capabilities during traversal.
Syntax
public Iterator<E> iterator()
Where:
E
is the element type declared in theArrayList
.
Parameters
- The iterator() method does not take any parameters.
Return Value
- Returns an Iterator over the elements in the list in sequence from first to last.
Exceptions
- No checked exceptions are thrown by
iterator()
itself. - The methods of the iterator (
next()
,remove()
) can throw exceptions:NoSuchElementException
if you callnext()
when no more elements exist.IllegalStateException
ifremove()
is called incorrectly (without a precedingnext()
).
How Does iterator() Work Internally?
iterator()
provides an object that maintains a cursor for traversing the list.- The iterator exposes three main methods:
hasNext()
– Checks if there is another element.next()
– Returns the next element.remove()
– Removes the last element returned bynext()
from the list.
- Using an iterator is safe for removing elements mid-loop, avoiding
ConcurrentModificationException
that can occur with standard for-each loops.
Examples of the iterator() Method
1. Basic Traversal Using Iterator
import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String[] args) { ArrayList<String> animals = new ArrayList<>(); animals.add("Dog"); animals.add("Cat"); animals.add("Rabbit"); Iterator<String> it = animals.iterator(); while (it.hasNext()) { String animal = it.next(); System.out.println(animal); } } }
Output:
Dog
Cat
Rabbit
2. Removing Elements Safely During Iteration
import java.util.ArrayList; import java.util.Iterator; public class Demo { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { int num = it.next(); if (num == 2) { it.remove(); // Safe removal during iteration } } System.out.println(numbers); // Output: [1, 3] } }
3. Common Mistake: Modifying During for-each Loop
ArrayList<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); // This will cause ConcurrentModificationException for (String name : names) { if (name.equals("Bob")) { names.remove(name); // Not allowed! } }
Solution: Always use iterator().remove()
when deleting during iteration.
Important Notes
- The iterator is forward-only and does not allow modification of list elements, only removal.
- Use
ListIterator
if you need bidirectional traversal or element replacement. - Iterators are fail-fast: they throw
ConcurrentModificationException
if the list is structurally modified outside of the iterator during traversal. - The order of elements traversed is the same as the order in the
ArrayList
.
Summary
Aspect | Details |
---|---|
Method Purpose | Obtain an iterator for sequential list traversal |
Syntax | Iterator<E> it = list.iterator() |
Common Methods | hasNext() , next() , remove() |
Modifications | Only safe way to remove elements while iterating |
Returns | Iterator object for the list |
Typical Use Cases | Traversing, conditional processing, safe removal |
Typical Use Cases
- Looping over all elements using a standard pattern.
- Safely removing items from a list while processing.
- Processing large lists without needing index-based access.