🔹 What is an Iterator?
An Iterator in Java is an object that allows you to traverse (iterate) through a collection (like ArrayList
, HashSet
, etc.) one element at a time.
It is part of the java.util
package and is the standard way to loop through collections when you don’t want to use traditional loops.
🔹 Key Points
- Iterator is a universal cursor for collections.
- Belongs to
java.util.Iterator
interface. - Works with the
Collection
framework (List
,Set
, etc.). - Allows read and remove operations while iterating.
- Unlike
Enumeration
, it is safer because it prevents ConcurrentModificationException if used properly.
🔹 Iterator Interface Methods
public interface Iterator<E> {
boolean hasNext(); // Returns true if there are more elements
E next(); // Returns the next element
void remove(); // Removes the last element returned (optional)
}
🔹 Example: Using Iterator with ArrayList
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
// Create a list
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Get the iterator
Iterator<String> itr = names.iterator();
// Iterate through the list
while (itr.hasNext()) {
String name = itr.next();
System.out.println(name);
// Example: remove "Bob"
if (name.equals("Bob")) {
itr.remove(); // Safe removal
}
}
System.out.println("After removal: " + names);
}
}
✅ Output:
Alice
Bob
Charlie
After removal: [Alice, Charlie]
🔹 Difference: Iterator vs. ListIterator
- Iterator: Works with all collections, can only iterate forward.
- ListIterator: Works only with
List
, can iterate both forward and backward, and allows adding/modifying elements.
🔹 For-each Loop vs Iterator
- For-each loop internally uses an
Iterator
but does not allow element removal. - Iterator gives more control (removal while iterating).