Iterable in Java
Understand the Iterable interface in Java: how it enables for-each loops, how to implement it on custom types, and common pitfalls.
Iterable<T> is the root interface of the Java Collections hierarchy. Any class that implements it can be used in a for-each (enhanced for) loop, which is the most common way to traverse a collection in Java. The single contract it defines — iterator() — returns an Iterator<T> that the loop compiler desugars into at compile time. Understanding Iterable and its companion Iterator is fundamental because every collection in the JCF builds on top of them.
What Iterable Defines
java.lang.Iterable<T> declares three methods:
| Method | Since | Description |
|---|---|---|
Iterator<T> iterator() |
Java 1.5 | Returns a new Iterator over the elements. Abstract — must implement. |
void forEach(Consumer<? super T> action) |
Java 8 | Default method: iterates and calls action for each element. |
Spliterator<T> spliterator() |
Java 8 | Default method: returns a Spliterator for parallel stream support. |
You only need to implement iterator(). The two default methods are provided automatically.
The Iterator Interface
Iterator<T> itself has three methods:
| Method | Description |
|---|---|
boolean hasNext() |
Returns true if more elements remain. |
T next() |
Returns the next element and advances the cursor. |
void remove() |
Removes the last element returned by next() from the underlying collection. Optional. |
How for-each Works Under the Hood
The compiler translates:
for (String s : list) {
System.out.println(s);
}
into:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
This is why calling list.remove() inside a for-each throws ConcurrentModificationException — the iterator detects that the collection was structurally modified outside of iterator.remove().
Example 1: Implementing Iterable on a Custom Type
import java.util.Iterator;
import java.util.NoSuchElementException;
// A simple fixed-size range of integers
public class IntRange implements Iterable<Integer> {
private final int start;
private final int end; // exclusive
public IntRange(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int current = start;
@Override
public boolean hasNext() {
return current < end;
}
@Override
public Integer next() {
if (!hasNext()) throw new NoSuchElementException();
return current++;
}
};
}
public static void main(String[] args) {
for (int n : new IntRange(1, 6)) {
System.out.print(n + " "); // 1 2 3 4 5
}
}
}
Example 2: Safe Removal During Iteration
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SafeRemoval {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie", "Dave"));
// Remove all names shorter than 4 characters using an explicit Iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
if (name.length() < 4) {
it.remove(); // safe: tells the iterator to remove
}
}
System.out.println(names); // [Alice, Charlie, Dave]
}
}
Common Mistakes
- Modifying the collection inside a for-each loop. The enhanced for loop uses a fail-fast iterator. Any structural modification (add, remove, clear) to the collection while iterating — other than through
iterator.remove()— throwsConcurrentModificationException. - Calling
next()without checkinghasNext(). Callingnext()on an exhausted iterator throwsNoSuchElementException. Always guard withhasNext()when using an iterator manually. - Returning the same iterator instance from
iterator(). Each call toiterator()must return a fresh, independent iterator object. Returning a cached instance means two simultaneous loops would share cursor state and corrupt each other. - Assuming
forEachuses a separate iterator.Iterable.forEachiterates over the same collection. Modifying the collection inside the lambda still risksConcurrentModificationExceptionfor non-concurrent collections. - Forgetting that arrays are not
Iterable. You can use an array in a for-each loop (the compiler handles it specially), but you cannot pass an array where anIterable<T>parameter is expected.
Best Practices
- Implement
Iterableon any domain type that represents a sequence of values to make it work naturally with for-each,Stream.of(), and third-party libraries. - Always throw
NoSuchElementException(not returnnull) fromnext()when the iterator is exhausted. - When you need to remove elements during iteration, use
iterator.remove()rather than the collection'sremove()method. - Prefer
Collection.removeIf(predicate)(Java 8+) over manual iterator removal for conciseness. - For read-only iteration, consider returning
Collections.unmodifiableList(...)so the iterator'sremove()throwsUnsupportedOperationException, signalling that mutation is not intended.
Interview Questions
1. What is Iterable in Java and why does it exist?
Iterable<T> is an interface in java.lang that represents any object that can be iterated over. It exists to provide a common protocol for traversal that the enhanced for-each loop and the Java Collections Framework can rely on. Any class that implements Iterable can be used in a for-each loop without the caller needing to know the underlying data structure.
2. What is the difference between Iterable and Iterator?
Iterable is a factory for iterators: it has one abstract method, iterator(), which produces an Iterator. Iterator is the cursor itself, holding traversal state (hasNext(), next(), remove()). A single Iterable object can produce multiple independent Iterator objects, each with their own position.
3. Why does modifying a collection inside a for-each throw ConcurrentModificationException?
Standard JCF iterators record the collection's modCount (a structural-modification counter) when they are created. On every call to next(), the iterator checks whether modCount still matches. If the collection was modified outside the iterator, the counts differ and the exception is thrown. This "fail-fast" behaviour prevents silent data corruption.
4. How do you remove elements safely while iterating?
Use an explicit Iterator and call iterator.remove(), or use Collection.removeIf(predicate) (Java 8+). Both methods update the internal modCount correctly. Alternatively, collect elements to remove in a separate list and call collection.removeAll(toRemove) after the loop.
5. Can you implement Iterable on a class that is not a collection?
Yes. Any class can implement Iterable as long as it can produce a meaningful sequence of values. Common examples include custom ranges, graph node neighbours, database result cursors, and tree traversal paths. The class simply needs to implement iterator() and return an appropriate Iterator.
6. What does Iterable.forEach do and how does it differ from a for-each loop?
Iterable.forEach(Consumer<? super T> action) is a default method added in Java 8. It iterates over elements and calls the consumer for each one, similarly to a for-each loop. The main difference is that forEach accepts a lambda or method reference, making it more concise for simple operations. Under the hood, most implementations still use an iterator.
7. What happens if iterator() is called twice on the same Iterable?
Each call should return a new, independent iterator starting at the beginning of the sequence. This allows multiple simultaneous loops or nested iterations over the same object. If the same iterator instance were returned, the second caller would start from wherever the first caller left off.
Summary
Iterable<T>is the root of the Collections hierarchy and enables the for-each loop.- It defines one abstract method,
iterator(), which returns anIterator<T>holding traversal state. - Each call to
iterator()must return a fresh iterator; sharing state between calls causes bugs. - Use
iterator.remove()orCollection.removeIf()for safe removal during iteration. - Implementing
Iterableon custom types integrates them with for-each loops and stream APIs.
Continue Learning
Previous: Collections Overview | Next: Collection
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.