The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The Iterator pattern is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.). This implementation provides a generic collection with an inner iterator class.
[Image: Iterator Pattern Class Diagram]
<!-- Add a class diagram showing Iterator interface, Collection class, and CollectionIterator -->
-
Iterator Interface (
Iterator.java)public interface Iterator<T> { T current(); void gotoNext(); void writeCurr(); boolean hasNext(); }
- Defines the interface for accessing and traversing elements
- Generic interface that works with any type
T - Provides methods for navigation and element access
-
Collection Class (
Collection.java)- Role: Aggregate/Container
- Purpose: Holds a collection of items and provides an iterator
- Key Features:
- Generic class that can hold any type of objects
- Uses varargs constructor for easy initialization
- Contains an inner
CollectionIteratorclass - Provides factory method to create iterators
public class Collection<T> { private T[] items; @SafeVarargs public Collection(T... items) { this.items = items; } public CollectionIterator iterator() { return new CollectionIterator(); } }
-
CollectionIterator Class (Inner Class)
- Role: Concrete Iterator
- Purpose: Implements the iteration logic for the collection
- Key Features:
- Maintains current position in the collection
- Implements all iterator interface methods
- Encapsulates traversal logic
- Provides safe iteration without exposing internal structure
private class CollectionIterator implements Iterator<T> { private int i = 0; public T current() { return items[i]; } public void gotoNext() { i++; } public boolean hasNext() { return i < items.length; } public void writeCurr() { System.out.println(items[i]); } }
// Create a collection of strings
Collection<String> stringCollection = new Collection<>("Apple", "Banana", "Cherry");
// Get an iterator
Iterator<String> iterator = stringCollection.iterator();
// Iterate through the collection
while (iterator.hasNext()) {
iterator.writeCurr(); // Print current element
iterator.gotoNext(); // Move to next element
}
// Output:
// Apple
// Banana
// CherryThis Iterator pattern implementation is ideal for:
- Collection Traversal: Safely iterating through any collection
- Data Structure Abstraction: Hiding internal structure details
- Multiple Traversals: Supporting multiple simultaneous iterations
- Uniform Interface: Providing consistent iteration across different collections
- Safe Iteration: Preventing direct access to internal data structures
- Encapsulation: Hides the internal structure of the collection
- Uniform Interface: Same interface for different collection types
- Multiple Iterators: Supports multiple simultaneous iterations
- Simplified Client Code: Clients don't need to know collection internals
- Single Responsibility: Separates traversal logic from collection logic
- Additional Complexity: Adds extra classes and interfaces
- Memory Overhead: Each iterator maintains its own state
- Limited Functionality: Basic iteration might be sufficient for simple cases
- Performance: May be slower than direct array access
-
Java Collections Framework
- ArrayList, LinkedList, HashSet iterators
- Enhanced for-loop implementation
-
Database Result Sets
- JDBC ResultSet iteration
- Cursor-based database access
-
File System Traversal
- Directory listing
- File tree navigation
-
GUI Components
- Menu item iteration
- Widget traversal
The TestIterator.java file demonstrates:
- Creating collections with different data types
- Using iterators to traverse collections
- Safe iteration without exposing internal structure
- Multiple iterator usage scenarios
- Generic Implementation: Uses Java generics for type safety
- Inner Class: Iterator is implemented as an inner class for encapsulation
- Varargs Constructor: Convenient initialization with multiple elements
- Simple Interface: Clean and minimal iterator interface
- Index-based Traversal: Uses array index for efficient access
- Fail-Fast Iterators: Consider implementing concurrent modification detection
- Remove Support: Add remove() method for element deletion during iteration
- Bidirectional Iteration: Consider supporting backward iteration
- Iterator Validity: Ensure iterators remain valid during collection changes
- Resource Management: Properly clean up iterator resources
- Concurrent Modification: Modifying collection while iterating
- Iterator Invalidation: Using iterator after collection modification
- Bounds Checking: Not checking hasNext() before accessing elements
- Memory Leaks: Not properly disposing of iterators
- Performance: Using iterator when direct access would be more efficient
- Composite: Often used together for tree traversal
- Factory Method: Iterator creation can use factory pattern
- Visitor: Can be combined for element processing during iteration
- Command: Iterator operations can be encapsulated as commands
- Add support for bidirectional iteration (previous/next)
- Implement fail-fast behavior for concurrent modifications
- Add remove() method for safe element deletion
- Support for filtered iteration (skip certain elements)
- Add support for parallel iteration
- Implement lazy loading for large collections
- Add support for nested collection iteration