Junior
How are the interfaces Iterable and Iterator related in Java?
sobes.tech AI
Answer from AI
Iterable represents a contract for objects whose contents can be iterated over. It contains a single method iterator(), which returns an object of type Iterator.
Iterator provides methods for sequential access to collection elements: hasNext() checks if there is a next element, next() returns the next element, and remove() (optional) removes the last element returned by next().
Thus, Iterable defines that an object is iterable, and Iterator provides the mechanism for actually traversing the elements.
// Example usage
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// names is Iterable
Iterator<String> iterator = names.iterator(); // Get Iterator
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}