Java Iterator Pattern
The Iterator Pattern in Java is a behavioral design pattern that provides a way to access elements of a collection sequentially without exposing its underlying representation. It decouples the traversal logic from the collection itself, allowing different traversal algorithms to be used interchangeably.
Key Components:
- Iterator Interface: Defines methods for traversing elements (
hasNext(), next(), remove()).
- Concrete Iterator: Implements the
Iterator interface and keeps track of the current position in the traversal.
- Iterable Interface: Defines a method (
iterator()) that returns an Iterator object.
- Concrete Iterable: Implements the
Iterable interface and provides the actual implementation of the iterator() method.
Example in Java:
import java.util.Iterator;
import java.util.NoSuchElementException;
// Custom Iterable Collection
class MyCollection<T> implements Iterable<T> {
private T[] elements;
private int size;
public MyCollection(T[] elements) {
this.elements = elements;
this.size = elements.length;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
// Concrete Iterator
private class MyIterator implements Iterator<T> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < size;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return elements[currentIndex++];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
// Usage
public class Main {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
MyCollection<String> collection = new MyCollection<>(names);
for (String name : collection) {
System.out.println(name);
}
}
}
Python Generators (Similar to Java Iterator)
In Python, generators provide a simpler way to create iterators using functions and the yield keyword. Generators are lazy iterators, meaning they generate values on-the-fly and do not store the entire sequence in memory.
Key Features:
- Lazy Evaluation: Values are generated one at a time and only when needed.
- Memory Efficient: Does not store all values in memory at once.
- Stateful: Maintains state between successive calls.
Example in Python:
def my_generator(elements):
for element in elements:
yield element
# Usage
names = ["Alice", "Bob", "Charlie"]
gen = my_generator(names)
for name in gen:
print(name)
Comparison:
| Feature | Java Iterator | Python Generator |
|---|
| Implementation | Requires Iterator and Iterable interfaces | Uses yield in a function |
| Memory Efficiency | Depends on the collection | Lazy evaluation (memory efficient) |
| State Management | Manual (e.g., currentIndex) | Automatic (handled by Python) |
| Syntax | More verbose | Concise and Pythonic |
Summary:
- Java Iterator Pattern: A structured way to traverse collections using interfaces (
Iterator, Iterable).
- Python Generators: A simpler, more concise way to create iterators using
yield, with built-in lazy evaluation.
Both serve the purpose of iterating over collections, but Python's generators are more lightweight and easier to implement.