Junior — Middle
What is the role of the Iterable interface in collection development and traversal?
sobes.tech AI
Answer from AI
The Iterable interface in Java defines an object that can be traversed using a for-each loop. It contains the iterator() method, which returns an Iterator object that allows sequential traversal of the collection's elements.
Role of Iterable:
- Provides a unified way to traverse elements in collections.
- Allows the use of
for (Element e : collection)syntax for convenience. - Makes collections compatible with various traversal algorithms.
Example:
List<String> list = Arrays.asList("a", "b", "c");
for (String s : list) {
System.out.println(s);
}
Here, List implements Iterable, enabling the use of a for-each loop to iterate over the elements.