A Java Iterator is an interface that provides a way to iterate over elements of a Collection (e.g., lists, sets) one by one. It allows developers to traverse a collection and perform operations on each element without exposing the underlying structure of the collection.
Key Features of Java Iterator:
- Sequential Access: It allows traversing elements of a collection in a sequence.
- Removal of Elements: You can remove elements from the collection during iteration.
- Generic Support: It supports generics, allowing type-safe iterations.
- Fail-Fast Behavior: Iterators throw a
ConcurrentModificationException
if the collection is modified while iterating (except for operations using the iterator’sremove()
method).
Iterator Interface Methods:
The Iterator
interface provides three main methods:
1. boolean hasNext()
:
- Checks if there are more elements in the collection.
- Returns true
if the iteration has more elements, otherwise false
.
E next()
:- Returns the next element in the collection and advances the iterator.
- Throws
NoSuchElementException
if there are no more elements. void remove()
:- Removes the last element returned by the iterator from the underlying collection.
- Can only be called once per call to
next()
, otherwise, it throwsIllegalStateException
.
Usage of Iterator:
Iterators are commonly used to iterate through collections like ArrayList
, HashSet
, LinkedList
, etc.
Example: Using an Iterator with a List:
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorExample {
public static void main(String args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Get an iterator for the list
Iterator<String> iterator = fruits.iterator();
// Iterate over the list
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
// Remove "Banana" from the list during iteration
if (fruit.equals("Banana")) {
iterator.remove();
}
}
// Output the modified list after iteration
System.out.println("After removal: " + fruits);
}
}
Output:
Apple Banana Orange After removal: [Apple, Orange]
Explanation:
hasNext()
checks if there is another element in the list.next()
returns the current element and advances the iterator.remove()
is used to safely remove the current element (in this case, "Banana") during iteration.
Advantages of Iterator:
- Encapsulation: Iterator hides the implementation details of the collection, allowing for uniform iteration across different collection types.
- Safe Removal: It provides a way to safely remove elements from the collection while iterating, without causing
ConcurrentModificationException
. - Unified Interface: The
Iterator
interface can be used with different types of collections, such asList
,Set
, andMap
.
Fail-Fast Behavior:
Iterators are typically fail-fast, meaning they throw a ConcurrentModificationException
if the collection is modified while being iterated (other than through the iterator's remove()
method). This is done to prevent unpredictable results during concurrent modifications.
Example of Fail-Fast Behavior:
List<String> items = new ArrayList<>(); items.add("A"); items.add("B"); Iterator<String> iterator = items.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (item.equals("A")) {
items.remove("A"); // Throws ConcurrentModificationException
}
}
When to Use Iterator:
- When you need to traverse through a collection without knowing the underlying data structure.
- When you need to remove elements during iteration,
Iterator
is the safest approach. - For read-only operations,
for-each
loops can also be used, but if removal is needed,Iterator
is preferred.
Conclusion:
The Java Iterator provides an efficient and safe way to traverse and manipulate collections. It ensures that you can iterate through collections without exposing their internal details and also offers the flexibility to remove elements safely during the iteration. The Iterator
is an important concept when working with Java collections and is especially useful when dealing with dynamic datasets.