Iterators are a fundamental design pattern in Java that provide a way to access elements of a collection sequentially without exposing its underlying representation. The Iterator pattern allows for different traversal techniques and provides a common interface for traversing different types of collections.
In Java, the Iterator interface is part of the Java Collections Framework and provides methods to iterate through a collection, check if there are more elements, and retrieve the next element.
Iterators are particularly useful because they give you the ability to safely add and remove elements while iterating through a collection. Without iterators, attempting to modify a collection during a for-each loop would result in a ConcurrentModificationException
.
The Iterator interface includes three key methods that help you traverse a collection:
boolean hasNext()
: Returns true
if the iterator has at least one more element to iterate through.E next()
: Returns the next element in the collection as long as hasNext()
is true
. Throws a NoSuchElementException
if hasNext()
is false
.void remove()
: Removes the current element in the collection and throws an IllegalStateException
if called again before calling next()
.The ListIterator<E>
extends the functionality of Iterator<E>
when working with List<E>
classes. It provides bidirectional traversal and the ability to add and update elements in addition to the standard iterator operations.
Additional methods in ListIterator include:
void add(E element)
: Inserts an object immediately before the current cursor position.void set(E element)
: Replaces the last element returned by next()
.hasPrevious()
and previous()
: Support traversing backwards through a list.Learn about the Java Iterator interface and its core methods.
Learn how to create custom Iterator implementations for your own data structures.
Understand the Iterable interface and how it relates to Iterator.
Explore common scenarios where Iterators are useful in real-world applications.
You can iterate over a list using either a for loop or a while loop. Here's what it looks like:
// Using a for loop with ListIterator
for (ListIterator<String> iterator = list.listIterator(); iterator.hasNext();) {
System.out.println(iterator.next() + " ");
}
// Using a while loop with ListIterator
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
Here are examples of using ListIterator to add, update, and remove elements from a list:
List<String> groceryList = new ArrayList<>();
ListIterator<String> groceryIterator = groceryList.listIterator();
groceryIterator.add("apples");
groceryIterator.add("bananas");
// List now contains: apples bananas
ListIterator<String> groceryIterator = groceryList.listIterator();
if (groceryIterator.hasNext()) {
groceryIterator.next(); // returns "apples"
groceryIterator.set("oranges");
}
// List now contains: oranges bananas
ListIterator<String> groceryIterator = groceryList.listIterator();
if (groceryIterator.hasNext()) {
groceryIterator.next(); // returns the first element
groceryIterator.remove();
}
// First element has been removed
remove()
without first calling next()
will throw an IllegalStateException
remove()
twice in a row without calling next()
in between will throw an IllegalStateException
set()
before calling next()
or after calling remove()
will throw an IllegalStateException
ConcurrentModificationException
Starter code for the iterators code-along exercise.
Solution code for the iterators code-along exercise.
Additional code-along exercises for this sprint.
Access the sprint challenge for this unit.