Iterator Overview

In Java, an Iterator is an interface that provides a way to access the elements in a collection (such as a List or Set) sequentially, without exposing the underlying data structure. It is a universal cursor that can be applied to any collection object. It can be accessed in single direction iterator.Here are some features of Iterators in Java:

* Sequential access: An Iterator allows you to access the elements in a collection sequentially, one at a time. This is useful when you need to perform an operation on each element in the collection.

* Read-only: Iterators are designed to be read-only, which means that you cannot modify the underlying collection while iterating over it. This ensures that the iteration is consistent and predictable. We can perform read and remove operation both but can't perform replace operation.

* Fail-fast behavior: When using an Iterator, if the underlying collection is modified while iterating over it (e.g. by adding or removing elements), the Iterator will detect this and throw a ConcurrentModificationException to prevent further access to the collection.

* Multiple Iterators: You can have multiple Iterators on the same collection at the same time, allowing you to iterate over the same collection in different ways simultaneously.

Here is an example of using an Iterator to iterate over a List in Java:

                
    List<String> fruits = new ArrayList<>();
    fruits.add("apple");
    fruits.add("banana");
    fruits.add("orange");

    Iterator<String> iterator = fruits.iterator();
    while (iterator.hasNext()) {
        String fruit = iterator.next();
        System.out.println(fruit);
    }
                
            

In this example, we create a List of Strings called fruits, and add three elements to it. We then create an Iterator called iterator by calling the iterator() method on the fruits List.

We then use a while loop to iterate over the fruits List using the hasNext() and next() methods of the Iterator. The hasNext() method returns true if there are more elements in the List, and the next() method returns the next element in the List.

For each element in the List, we print it out using System.out.println(). The output of this code would be:

                
    apple
    banana
    orange
                
            

This example shows how you can use an Iterator to iterate over a collection in a simple and predictable way.