Sobes.tech
Senior

What is the difference between Iterable and Iterator interfaces?

sobes.tech AI

Answer from AI

The Iterable and Iterator interfaces in Java are related to iterating over collections but serve different roles:

  • Iterable is an interface implemented by a collection or any object that supports element traversal. It contains a single method iterator(), which returns an Iterator object. This allows the use of a for-each loop to iterate over elements.

  • Iterator is an interface that provides methods for sequential access to collection elements: hasNext() to check if there is a next element, and next() to retrieve that element. There is also a remove() method to delete the current element.

Example:

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

In summary:

  • Iterable is the source of an iterator, allowing you to obtain an Iterator.
  • Iterator is the mechanism itself for traversing collection elements.