The Iterator<E> Interface Overview
What you'll learn: You'll understand the three core methods that make up the Iterator<E> interface and how each enables controlled traversal through collections.
What Is Iterator<E>?
The Iterator<E> interface is Java's standard mechanism for stepping through collection elements one at a time. Think of it like a bookmark that knows its current position in a book and can move forward page by page. The interface defines exactly three methods that work together to provide safe, sequential access to elements.
The Three Methods
boolean hasNext()
This method checks whether there are more elements remaining to visit. It returns true if another element exists, false otherwise. Think of it as asking "Is there a next page?" before trying to turn the page.
E next()
This method returns the next element in the iteration and advances the iterator's position forward. It's like reading the current page and then moving your bookmark to the next one. If you call next() when no elements remain, it throws a NoSuchElementException.
void remove()
This optional method removes the last element returned by next() from the underlying collection. You must call next() before calling remove(), and you can only call remove() once per next() call. Not all iterators support removal—some throw UnsupportedOperationException.
Typical Usage Pattern
Iterator<String> iterator = someCollection.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
// Process element
}
The hasNext()-next() pair forms the backbone of iteration, while remove() provides a safe way to delete elements during traversal without causing concurrent modification issues.
Key Takeaway: The Iterator<E> interface defines three methods—hasNext() checks for remaining elements, next() retrieves and advances, and remove() safely deletes the last-returned element.