Java Design Program · CD04
Implement a Custom Iterator in Java
The enhanced for loop works with any class that implements Iterable. Return an Iterator that knows the next value and when to stop.
Problem Statement
Write a Range class for the integers from start (inclusive) to end (exclusive) so that it can be used in a for-each loop.
An empty range produces no values, and calling next() after the last value throws NoSuchElementException.
Input/Output Examples
for (int n : new Range(1, 4))Output1 2 3Explanation: the end value 4 is excluded.new Range(5, 5)Output0 itemsExplanation: start equals end.next() after the last valueOutputNoSuchElementExceptionExplanation: the Iterator contract requires it.Visual Explanation
- iterator()next1a fresh position
- hasNext()check1 < 4true → next() = 1
- …returned123next moves to 4
- hasNext()check4 < 4false loop ends
- Done1 2 3
iterator() once, then alternates hasNext() and next() until hasNext() returns false.Each call to iterator() returns a new iterator with its own position, so the same Range can be looped over many times, even in nested loops.
Approaches
Both approaches make Range iterable. The first writes the iterator by hand; the second reuses the iterator of an IntStream.
Approach 1: Hand-Written Iterator (Recommended)
Idea: return an anonymous Iterator that stores the next value and compares it with end.
- Implement
Iterable<Integer>. - In
iterator(), create an iterator with its ownnextfield. hasNext()returnsnext < end;next()returns and advances, or throws.
Time: O(1) per element · Space: O(1).
Approach 2: Delegate to IntStream
Idea: return IntStream.range(start, end).iterator(), which already follows the contract.
- Implement
Iterable<Integer>. - Return the iterator of an
IntStreamfor the range. - The JDK handles
hasNext(),next()and the exception.
Time: O(1) per element · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Hand-Written Iterator (Recommended)
Shows exactly how the for-each loop works, which is what interviewers usually want.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class RangeIteratorClass {
// Implementing Iterable is all a class needs to work in a for-each loop
static class Range implements Iterable<Integer> {
private final int start;
private final int end; // exclusive
Range(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int next = start; // each iterator has its own position
@Override
public boolean hasNext() {
return next < end;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return next++;
}
};
}
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int n : new Range(1, 4)) {
sb.append(n).append(' ');
}
System.out.println("Range(1, 4): " + sb.toString().trim());
int count = 0;
for (int ignored : new Range(5, 5)) {
count++;
}
System.out.println("Range(5, 5) items: " + count);
Iterator<Integer> it = new Range(0, 1).iterator();
it.next();
try {
it.next();
} catch (NoSuchElementException e) {
System.out.println("next() past the end -> NoSuchElementException");
}
}
}
Range(1, 4): 1 2 3 Range(5, 5) items: 0 next() past the end -> NoSuchElementException
Time complexity: O(1) per element · Space complexity: O(1).
Approach 2: Delegate to IntStream
Less code, and a good example of reusing existing iterators instead of writing new ones.
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.stream.IntStream;
public class RangeIteratorStream {
// Delegates to the iterator of an IntStream instead of writing the Iterator by hand
static class Range implements Iterable<Integer> {
private final int start;
private final int end;
Range(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return IntStream.range(start, end).iterator(); // a PrimitiveIterator.OfInt
}
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int n : new Range(1, 4)) {
sb.append(n).append(' ');
}
System.out.println("Range(1, 4): " + sb.toString().trim());
int count = 0;
for (int ignored : new Range(5, 5)) {
count++;
}
System.out.println("Range(5, 5) items: " + count);
Iterator<Integer> it = new Range(0, 1).iterator();
it.next();
try {
it.next();
} catch (NoSuchElementException e) {
System.out.println("next() past the end -> NoSuchElementException");
}
}
}
Range(1, 4): 1 2 3 Range(5, 5) items: 0 next() past the end -> NoSuchElementException
Time complexity: O(1) per element · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Hand-Written Iterator | O(1) per element | O(1) |
| Delegate to IntStream | O(1) per element | O(1) |
Both iterators produce each value in constant time and store only their current position, so iterating over a range of n values costs O(n) time and O(1) memory.
Interview Tips and Recommended Approach
- Return a new iterator each time. Storing the position in
Rangeitself breaks nested loops. - Throw
NoSuchElementExceptionfromnext()at the end, as the contract requires. - Leave
remove()alone if removal makes no sense; its default throwsUnsupportedOperationException. - Mention fail-fast iterators. JDK collections throw
ConcurrentModificationExceptionwhen changed during iteration.
Recommended Approach: Hand-Written Iterator
Why: it shows the full iterator contract in a few lines, which makes it the best answer when the question is about how for-each loops work.