Iterator
In Java, an Iterator is an interface that provides a way to traverse or iterate over a collection of objects, such as lists, sets, or other data structures. It is part of the java.util
package and allows us to access elements of a collection one by one.
Here are some key points about the Iterator
interface:
Basic Methods
boolean hasNext()
: Returnstrue
if there are more elements to iterate over, andfalse
otherwise.E next()
: Returns the next element in the iteration.void remove()
: Removes the last element returned by the iterator from the underlying collection. This is an optional operation and may not be supported by all collections.
Usage Example
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
// Create a collection
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Get an Iterator
Iterator<String> iterator = fruits.iterator();
// Iterate over the collection
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
// Optional remove operation
if (fruit.equals("Banana")) {
iterator.remove();
}
}
// After removal
System.out.println(fruits);
}
}
Advantages
Iterator
allows the user to traverse the collection without exposing the underlying representation.- It provides a fail-safe mechanism to remove elements during iteration.
Limitations
Iterator
only moves forward and cannot be reset or move backward.- Removing an element using
remove()
can only be done once per call tonext()
. If called multiple times consecutively without anext()
, it will throwIllegalStateException
.
Enhanced for-loop (for-each)
While an Iterator
is useful, Java provides an enhanced for
loop (for-each
loop) as a more convenient way to iterate through collections, although we can’t modify the collection during iteration with this method.
for (String fruit : fruits) {
System.out.println(fruit);
}