In Java, an Iterator is an interface that provides a way to access elements of a collection object one by one, without exposing the underlying implementation of the collection. It allows you to loop through a collection and retrieve each element one by one, without having to know the details of how the collection is implemented.
The Iterator interface has three methods that you can use to traverse a collection:
- hasNext(): returns true if there is at least one more element in the collection to retrieve.
- next(): returns the next element in the collection.
- remove(): removes the last element returned by the iterator from the underlying collection.
Here is an example of how to use an Iterator in Java:
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
// Create an iterator for the ArrayList
Iterator<String> iterator = list.iterator();
// Loop through the ArrayList and print each element
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}
In this example, we create an ArrayList of strings and add some elements to it. We then create an Iterator for the ArrayList and use it to loop through the ArrayList and print each element to the console. The output of the above code will be:
apple
banana
cherry
As you can see, the Iterator allows us to loop through the ArrayList without having to know the details of how it is implemented. This makes our code more flexible and easier to maintain.