Senior
What is the difference between Iterable and Iterator?
sobes.tech AI
Answer from AI
In Java, Iterable is an interface that represents a collection of objects that can be traversed using a for-each loop. It contains a single method iterator(), which returns an Iterator object.
Iterator is an interface that provides methods for sequentially traversing the elements of a collection: hasNext(), next(), and optionally remove().
In other words:
Iterableis a collection that can be iterated over.Iteratoris an object that performs the traversal of the collection's elements.
Example:
List<String> list = Arrays.asList("a", "b", "c");
Iterable<String> iterable = list;
Iterator<String> iterator = iterable.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}