Iterator and methods in Iterator

Iterator and methods in Iterator

An iterator in Java is an interface provided by the Java Collections Framework that allows for traversing through a collection of elements, one at a time. It provides a way to access the elements of a collection without exposing its underlying implementation details. The `Iterator` interface defines methods for navigating and accessing elements in a collection in a consistent and uniform manner.

Iterator and methods in Iterator

Methods in the Iterator Interface:

  • 1. `boolean hasNext()`:
    • Returns `true` if the iteration has more elements, i.e., if there are still elements remaining to be traversed in the collection.
    • Returns `false` otherwise.
  • 2. `E next()`:
    • Returns the next element in the iteration.
    • Advances the iterator to the next position in the collection.
    • Throws a `NoSuchElementException` if there are no more elements to iterate over.
  • 3. `void remove()` (Optional):
    • Removes the last element returned by the iterator from the underlying collection.
    • This method is optional and may not be supported by all iterators. It throws an `UnsupportedOperationException` if the `remove()` operation is not supported.

Example Usage of Iterator:

Here’s an example demonstrating how to use the `Iterator` interface to iterate over elements in a collection:

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

public class IteratorExample {
    public static void main(String[] args) {
        // Create a list of integers
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        // Get an iterator for the list
        Iterator<Integer> iterator = numbers.iterator();

        // Iterate over the elements using the iterator
        while (iterator.hasNext()) {
            int number = iterator.next();
            System.out.println("Number: " + number);

            // Remove even numbers from the list
            if (number % 2 == 0) {
                iterator.remove(); // Removes the current element from the list
            }
        }

        // Print the modified list after removing even numbers
        System.out.println("List after removing even numbers: " + numbers);
    }
}
```

In this example:

  • We create a list of integers and add some elements to it.
  • We obtain an iterator for the list using the `iterator()` method.
  • We use a `while` loop along with the `hasNext()` and `next()` methods to iterate over the elements in the list.
  • We use the `remove()` method to remove even numbers from the list during iteration.

The iterator provides a simple and uniform way to traverse collections, making it easier to work with various types of collections in Java.