0% completed
Iterators provide a standard way to traverse through collections without exposing their underlying structure. They are part of the Java Collections Framework and allow you to safely iterate and, if needed, remove elements during traversal. The basic syntax for using an iterator is as follows:
Iterator<E> iterator = collection.iterator(); while(iterator.hasNext()) { E element = iterator.next(); // Process the element }
This syntax shows that you first obtain an iterator from a collection using the iterator()
method. Then, you repeatedly check for more elements with hasNext()
. If an element exists, you retrieve it using next()
. This loop continues until all elements have been processed.
In this example, we create an ArrayList of fruit names and use an iterator to traverse and print each element.
Explanation:
fruits
and add several fruit names.hasNext()
.next()
and printed.In this example, we demonstrate how to remove elements from an ArrayList while iterating over it using the iterator's remove()
method.
Explanation:
items
and add several strings, including duplicates.remove()
method is called to delete that element.Iterators offer a safe and uniform way to traverse and manipulate collections in Java. In the examples above, we saw how to iterate over an ArrayList using the hasNext()
and next()
methods, and how to remove elements during iteration using the remove()
method. This approach encapsulates the traversal logic, allowing you to focus on processing each element without exposing the internal structure of the collection.
.....
.....
.....