Iterable and Iterator
Separating a Sequence from Its Traversal
When you process records, labels, or measurements one at a time, you need both a source of elements and a way to track your progress. Java separates these responsibilities. This lesson uses Java 17 notation; var keeps the examples focused on traversal rather than type declarations.
Two roles, one sequence
An iterable is an object that can supply an iterator through its iterator() method. An iterator is an object that maintains progress through one traversal and provides elements successively. Java names the corresponding interfaces Iterable and Iterator.
A list can supply an iterator without exposing how its elements are stored. Your traversal code asks for the next element instead of managing array positions or following internal links.
Question | Iterable source | Iterator |
|---|---|---|
What does it represent? | Something whose elements can be traversed | Progress through a particular traversal |
Which central method does it provide? | iterator() | hasNext() and next() |
What do you request from it? | A traversal object | Availability information or another element |
For ordinary Java lists, separate calls to iterator() create independent traversal state. Advancing one iterator does not advance another. However, assigning an existing iterator to another variable gives you two references to the same traversal object. The Iterable interface alone does not promise that every possible source supports repeatable, independent traversals; check the source's contract.
Checking, advancing, and exhaustion
hasNext() reports whether another element is available. It does not consume that element. next() returns the next element and advances the traversal. Calling hasNext() repeatedly therefore does not skip records.
For an unchanged finite source containing n elements, after k successful calls to next():
Here, successful means that the call returned an element. Availability checks do not contribute to k. Once no elements remain, hasNext() returns false, and calling next() throws NoSuchElementException. It does not return a special final value or restart automatically.
Writing loops and managing traversal
For an existing list named records, a standard explicit traversal is:
var it = records.iterator();
while (it.hasNext()) {
var record = it.next();
System.out.println(record);
}The iterator is obtained once before the loop. Each successful check permits one read. Keep each advancing read visible: putting a second next() call in the body consumes a second element, even if you ignore its return value.
An enhanced for loop expresses the common case more briefly:
for (var record : records) {
System.out.println(record);
}For an iterable source, this loop uses an iterator behind the scenes. An explicit iterator is useful when your code needs direct control over checking and advancing. Arrays also support enhanced for loops, although Java arrays do not implement Iterable.
An iterator's remove() operation, when supported, removes the last element returned by next(). It is optional, and it may be called only once per successful next() call. Merely reading elements does not perform removal.
What to remember
- An iterable supplies a traversal; an iterator tracks its progress.
- hasNext() checks availability, while next() consumes one position.
- Exhaustion does not reset an iterator or produce null as a sentinel.
- Separate variables do not guarantee separate iterator objects.
- Use an enhanced for loop for straightforward traversal and an explicit iterator when you need direct control.
Example: Scanning Parcel Masses
Example: A distribution centre stores four parcel masses in kilograms. An iterator tracks progress through one traversal of these masses. Assume Java 17 with standard java.util imports, and the list remains unchanged throughout the problem.
var masses = List.of(11, 16, 8, 13);
var scan = masses.iterator();Work through the parts in order, keeping the same scan iterator unless a part explicitly creates another one.
a) What values do the two checks return, and what mass does the first read return?
boolean firstCheck = scan.hasNext();
boolean secondCheck = scan.hasNext();
int firstMass = scan.next();Initially, the iterator has ________ unread elements. The first check returns true because a first element exists. It does not consume that element, so the second check also returns true.
The call to next() then returns the first stored value, 11 kg, and advances past that position. There are now ________ unread elements.
The results are firstCheck = true, secondCheck = true, and firstMass = 11 kg. The mass is still present in the source list; only traversal progress has changed.
b) Starting from that position, what total mass does this loop accumulate?
int remainingMass = 0;
while (scan.hasNext()) {
remainingMass += scan.next();
}The first parcel has already been read, so the loop begins with the second mass. Its first successful check permits a read of 16 kg, bringing the running total to 16 kg.
The next check permits a read of 8 kg. The running total is then ________. The third read returns 13 kg, giving:
After those three reads, the number of unread elements is ________. The next availability check returns false, so the loop ends without attempting another read.
The final accumulated mass is 37 kg. The earlier 11 kg is excluded because this loop continues an existing traversal rather than beginning another one.
c) After part b, what mass does restart.next() return, and what does scan.hasNext() return?
var restart = masses.iterator();
int restartMass = restart.next();
boolean originalAvailable = scan.hasNext();Calling masses.iterator() creates a separate list iterator whose progress begins at the first element. Its first read therefore returns 11 kg.
The original scan iterator has already completed its traversal. Creating or advancing restart does not change scan, so the original iterator still reports no available element.
The results are restartMass = 11 kg and originalAvailable = false. The source still contains all four parcel masses because none of these reads removes an element.
A Java program executes the following code with the standard java.util imports. The list remains unchanged throughout execution.
var colours = List.of("red", "blue");
var it = colours.iterator();
it.next();
it.next();
boolean available = it.hasNext();
var result = it.next();What happens when the final statement attempts to read another element?
A warehouse program creates two iterators over the same Java list of label codes. The list is not modified.
var labels = List.of("L", "M", "N");
var a = labels.iterator();
var b = labels.iterator();Execute the calls in the table from top to bottom. Enter each returned letter without quotation marks, or enter true or false for a boolean result. Each row continues from the state left by the preceding row.
| Call number | Expression | Returned value |
| 1 | a.next() | |
| 2 | a.hasNext() | |
| 3 | b.next() | |
| 4 | a.next() | |
| 5 | b.next() | |
| 6 | a.next() | |
| 7 | a.hasNext() |