The Iterator Interface in Java
In Java, the Iterator
interface is a member of the java.util
package and is used to iterate over the elements of a collection. An Iterator
allows you to access the elements of a collection one at a time, in a sequential order, and provides methods for moving through the elements of the collection and for removing elements from the collection.
The Iterator
interface is an interface and does not have any implementation class. It is used as the superinterface for several subinterfaces and concrete classes, such as ListIterator
and Enumeration
.
Here is an example of how to use the Iterator
interface:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// Create a collection
ArrayList<String> collection = new ArrayList<>();
// Add elements to the collection
collection.add("A");
collection.add("B");
collection.add("C");
// Get an iterator for the collection
Iterator<String> iterator = collection.iterator();
// Iterate over the elements of the collection
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
// Remove the current element from the collection
iterator.remove();
}
}
}
In this example, we create a collection of strings using an ArrayList
and add elements to the collection. We then get an Iterator
for the collection using the iterator()
method and use the hasNext()
and next()
methods of the Iterator
to iterate over the elements of the collection. We also use the remove()
method of the Iterator
to remove the current element from the collection.
The Iterator
interface is a useful and convenient way to iterate over the elements of a collection and perform operations on them. It is an essential part of the Java Collections Framework and is used in a wide range of applications.