Java
Iterable
Learn for-each support with Iterable.
The Iterable<T> interface
Iterable<T> is the interface that lets a class be used in a for-each loop. Any class that implements Iterator<T> iterator() becomes Iterable. The List, Set and Queue interfaces all inherit Iterable.
Once your class implements Iterable, a for (String s : myObject) loop works. This makes a non-collection structure traversable; for example a tree, a list of lines or a number range can be made Iterable.
A custom Iterable example
When a Names class implements Iterable<String>, it works like this: it holds a List<String> items field; the iterator() method returns items.iterator(). Outside, when you write for (String n : names) Java calls this method.
This is a clean way to hide inner data and expose only read access. Users cannot see the list directly but can traverse it through the Iterator. Writing an Iterator from scratch is not needed; the inner list is already Iterable.
Exercise Write a custom Iterable class
Define class Names implements Iterable<String>. Hold a List<String> items = new ArrayList<>(); field; add void add(String n) that calls items.add(n);. Implement @Override public Iterator<String> iterator() that returns items.iterator(). In main, create Names names = new Names();, add two names, then print with for (String n : names) System.out.println(n);.
Show example solution
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
class Names implements Iterable<String> {
List<String> items = new ArrayList<>();
void add(String n) { items.add(n); }
public Iterator<String> iterator() { return items.iterator(); }
}
public class Main {
public static void main(String[] args) {
Names names = new Names();
names.add("Ayşe");
names.add("Alex");
for (String n : names) {
System.out.println(n);
}
}
}
Test yourself
-
What do you gain when a class is Iterable?
- Comparable ability
- Sorting ability
- for-each loop support
- Multiple inheritance
Show answer
for-each loop support — An Iterable class can be traversed with for-each.
-
Complete the class declaration
class Names implements Iterable<String> {
public Iterator<String> ____() {
return items.iterator();
}
}
Show answer
class Names implements Iterable<String> {
public Iterator<String> iterator() {
return items.iterator();
}
}
-
Match the Iterable concepts
- Iterable<T>
- Interface enabling for-each
- iterator()
- Single required method
- List
- Inherits Iterable
- for-each
- Short loop syntax
Next lesson: Spliterator