java iterator

java

In Java, an Iterator is an interface that is used to iterate over a collection of elements. It provides a way to access the elements of a collection one at a time, without exposing the underlying implementation of the collection.

An Iterator has three main methods:

  1. hasNext(): This method returns true if there are more elements to iterate over, and false if there are no more elements.
  2. next(): This method returns the next element in the iteration.
  3. remove(): This method removes the current element from the collection.

Here is an example of how you can use an Iterator to iterate over a List in Java:

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

public class Main {
  public static void main(String[] args) {
    // create a list of strings
    List<String> list = new ArrayList<>();
    list.add("apple");
    list.add("banana");
    list.add("cherry");

    // create an iterator for the list
    Iterator<String> iterator = list.iterator();

    // iterate over the list
    while (iterator.hasNext()) {
      String element = iterator.next();
      System.out.println(element);
    }
  }
}

This will output the following:

apple
banana
cherry

In this example, we create a List of strings and an Iterator for the list. We then use the hasNext() and next() methods of the Iterator to iterate over the elements of the list and print them to the console.

Note: The Iterator interface is part of the Java Collection Framework, which provides a set of interfaces and classes for working with collections of objects. The Iterator interface is implemented by many classes in the framework, such as ArrayList, LinkedList, and HashSet, which allows you to use an Iterator to iterate over elements of these classes.