Java Iterator: Safe and Standard Way to Traverse Collections
Java Iterator: Safe and Standard Way to Traverse Collections
β What is an Iterator?
It's an interface in java.util
.
- Provides a way to traverse a collection one element at a time.
- Works with all
Collection
types (e.g.,List
,Set
,Queue
). - Safe way to remove elements during iteration.
π§° Methods of Iterator
Method | Description |
---|---|
hasNext() |
Returns true if there are more elements. |
next() |
Returns the next element in the collection. |
remove() |
Removes the current element (optional operation). |
π Basic Example
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String lang = it.next();
System.out.println(lang);
}
}
}
Output:
Java
Python
C++
ποΈ Removing Elements Safely
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String value = it.next();
if (value.equals("Two")) {
it.remove(); // Safe removal during iteration
}
}
System.out.println(list); // Output: [One, Three]
π« Note: Donβt use list.remove(item)
inside a loop β it causes ConcurrentModificationException
.
π Enhanced For-Loop vs Iterator
Feature | Enhanced For-Loop | Iterator |
---|---|---|
Easy to use | β Yes | β Slightly verbose |
Can remove elements safely | β No | β Yes |
Works with collections | β Yes | β Yes |