Iterable and Iterator Interfaces
Overview
The Iterable and Iterator interfaces provide a standardized way to iterate over collections of objects.
- Iterable: An object that can return an
Iterator(e.g., lists, stacks, queues). - Iterator: An object that tracks the current position in a collection and enables traversal.
Interface Definitions
Iterable Interface
public interface Iterable<Item> {
// Returns an iterator over elements of type `Item`
public Iterator<Item> iterator();
}
Iterator Interface (Nested)
public interface Iterator<Item> {
// Checks if there are more elements to iterate over
public boolean hasNext();
// Returns the next element in the iteration
public Item next();
// Removes the last element returned by the iterator (optional operation)
public void remove();
}
Example Usage
Long Form (Explicit Iterator)
Iterator<String> i = stack.iterator();
while (i.hasNext()) {
String s = i.next();
StdOut.println(s);
}
Shorthand (Enhanced For-Each Loop)
for (String s : stack) {
StdOut.println(s);
}
Both code snippets achieve the same result, but the enhanced for loop abstracts the Iterator logic.
Key Notes
remove()Method:- Optional: Not all iterators implement
remove(). If unsupported, it throws anUnsupportedOperationException. - Behavior: Removes the last element returned by
next(). Must be called after anext().
- Optional: Not all iterators implement
- Implementing
Iterable:- Classes implementing
Iterablemust provide aniterator()method that returns a validIterator. - Enables compatibility with the enhanced
forloop syntax.
- Classes implementing
- Fail-Fast vs. Fail-Safe:
- Iterators may throw a
ConcurrentModificationExceptionif the collection is modified during iteration (fail-fast behavior).
- Iterators may throw a
- Generic Types:
- Replace
Itemwith the actual data type (e.g.,String,Integer) for type safety.
- Replace
Best Practices
- Prefer the enhanced
forloop for readability when no explicitremove()is needed. - Avoid modifying the underlying collection while iterating unless the iterator supports it.
