Iterator is an interface in Java that allows sequential access to elements of a collection. It is part of the Java Collection Framework and is mainly used to traverse List, Set, and other collections safely.
The Iterator interface provides methods to check and retrieve elements one by one.
hasNext() – checks if next element existsnext() – returns the next elementremove() – removes the current elementClick the buttons to simulate how an Iterator traverses an ArrayList.
// Example of using Iterator with ArrayList
import java.util.ArrayList;
import java.util.Iterator;
class IteratorDemo {
public static void main(String[] args) {
ArrayList names = new ArrayList<>();
names.add("Java");
names.add("Python");
names.add("C++");
Iterator it = names.iterator();
while(it.hasNext()) {
String value = it.next();
System.out.println(value);
}
}
}
Java
Python
C++
The iterator moves through the collection one element at a time using hasNext() and next().
remove()