An Iterator in Java is one of the most commonly used cursors in the Java Collections Framework. It is used to traverse or iterate through elements of a collection one by one.
- It is used to traverse elements in the forward direction only.
- Removes elements safely during traversal using remove().
- Iterator is a universal cursor that applies to all collection types — List, Set, and Queue.
Declaration of Iterator
public interface Iterator<E>
Here, E represents the type of elements to be iterated over.
Object Creation of Iterator
An Iterator object is created by calling the iterator() method on a collection object. Here, we will use an Iterator to traverse and print each element in an ArrayList.
Collection<String> names = new ArrayList<>();
Iterator<String> itr = names.iterator();
import java.util.ArrayList;
import java.util.Iterator;
public class Geeks {
public static void main(String[] args) {
// Create an ArrayList and add some elements
ArrayList<String> al = new ArrayList<>();
al.add("A");
al.add("B");
al.add("C");
// Obtain an iterator for the ArrayList
Iterator<String> it = al.iterator();
// Iterate through the elements and print each one
while (it.hasNext()) {
// Get the next element
String n = it.next();
System.out.println(n);
}
}
}
Output
A B C
Hierarchy of Iterator
Iterator is part of the java.util package and is implemented by all collection classes through their subinterfaces.