Data Structures
Iterators
In Java, Iterator is an interface within the java.util package used to traverse the elements of a collection sequentially. It allows you to access and potentially remove elements from a collection without needing to know the collection’s underlying implementation details.
Key methods of the Iterator interface:
boolean hasNext(): This method returnstrueif there are more elements in the iteration, andfalseotherwise.E next(): This method returns the next element in the iteration and advances the iterator’s internal pointer. It throws aNoSuchElementExceptionif there are no more elements.void remove(): This optional method removes the last element returned bynext()from the underlying collection. It can only be called once per call tonext(), and attempting to call it at other times or multiple times after a singlenext()call will result in anIllegalStateException.
Iterator and the enhanced for-each loop:
The enhanced for-each loop (introduced in Java 5), which can be used for simple iteration without element removal, uses an Iterator internally. For example:
List<String> names = new ArrayList<>();
// Populate list
for (String name : names)
{
System.out.println(name);
}How to use an Iterator explicitly:
- Obtain an Iterator: Call the
iterator()method on a Collection object (e.g.,ArrayList,HashSet,LinkedList) to get anIteratorobject for that collection.
- Iterate through elements: Use a
whileloop withhasNext()andnext()to process each element.
- Remove elements (optional): If needed, use the
remove()method of the iterator to safely remove elements during iteration.
while (it.hasNext())
{
String name = it.next();
if (name.equals("John"))
{
it.remove(); // Removes "John" from the 'names' list
}
}Exceptions:
There are several exceptions that can be thrown by the remove method or other code when an Iterator is active.
UnsupportedOperationException: If theremoveoperation is not supported by this iteratorIllegalStateException: If thenextmethod has not yet been called or theremovemethod has already been called after the last call to thenextmethod.ConcurrentModificationException: Modifying the underlying collection directly (e.g., usingadd()orremove()methods of the collection itself) while an Iterator is active will lead to aConcurrentModificationExceptionwhennext()is called. Use the Iterator’sremove()method for safe modification during iteration.
Additional Functionality:
ListIterator: ForListimplementations, a more specializedListIteratoris available, which provides additional functionalities like bidirectional traversal (hasPrevious(),previous()) and element modification (set(),add()).forEachRemaining(): Since Java 8, theIteratorinterface includes aforEachRemaining()method, allowing you to process remaining elements using a lambda expression.