What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection.

The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.

In Core Java, the Iterator interface is a part of the Java Collections Framework and is used to iterate over a collection of objects, such as a List, Set, or Map. It provides methods for sequentially accessing elements in a collection without exposing the underlying implementation of the collection.

The key methods of the Iterator interface include:

  1. boolean hasNext(): Returns true if the iteration has more elements.
  2. Object next(): Returns the next element in the iteration.
  3. void remove(): Removes the last element returned by the iterator from the underlying collection. This method is optional and may not be supported by all implementations.

Here’s a simple example of using an Iterator with a List:

java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("Java");
myList.add("C++");
myList.add("Python");

// Using Iterator to iterate over the list
Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
String language = iterator.next();
System.out.println(language);
}
}
}

In this example, the Iterator is obtained from the List, and the hasNext() and next() methods are used to iterate through the elements of the list.

It’s important to note that the enhanced for loop introduced in Java 5 provides a more concise way to iterate over collections, but understanding the Iterator interface is still valuable, especially when dealing with more complex scenarios or when you need to modify the collection while iterating.