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:
-
Iterableis an interface implemented by a collection or any object that supports element traversal. It contains a single methoditerator(), which returns anIteratorobject. This allows the use of afor-eachloop to iterate over elements. -
Iteratoris an interface that provides methods for sequential access to collection elements:hasNext()to check if there is a next element, andnext()to retrieve that element. There is also aremove()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:
Iterableis the source of an iterator, allowing you to obtain anIterator.Iteratoris the mechanism itself for traversing collection elements.