Sobes.tech
Junior — Middle

How does the iterator interface differ from the collection interface that supports iteration?

sobes.tech AI

Answer from AI

The iterator interface (for example, Iterator in Java) provides methods for sequentially traversing the elements of a collection: hasNext(), next(), and optionally remove(). It is responsible only for the iteration process itself — how to get the next element and check if there are more elements.

The collection interface that supports iteration (for example, Iterable) provides the iterator() method, which returns an iterator object. Thus, a collection is a container that stores elements and can create an iterator to traverse these elements.

Example:

Iterable<String> collection = List.of("a", "b", "c");
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

In summary:

  • A collection is a data structure that contains elements and can create an iterator.
  • An iterator is an object that allows sequential access to the elements of a collection.
How does the iterator interface differ from the… - sobes.tech