Junior — Middle
Which method from the Iterable interface do you usually use to iterate over elements?
sobes.tech AI
Answer from AI
In the Java Iterable interface, the iterator() method is commonly used to traverse elements. It returns an Iterator object, which allows sequential access to the collection's elements.
Example of usage:
Iterable<String> iterable = List.of("apple", "banana", "cherry");
Iterator<String> iterator = iterable.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}
The for-each loop is also frequently used, which internally uses iterator():
for (String item : iterable) {
System.out.println(item);
}
Thus, the iterator() method is the main way to traverse elements in an Iterable.