Каково отношение между интерфейсами Iterable, Iterator и конструкцией 'for-each' в Java?
sobes.tech AI
Answer from AI
-
Iterableis an interface implemented by classes whose objects can be iterated over. It has a methoditerator(), which returns anIteratorobject. -
Iteratoris an interface that provides methods for step-by-step traversal of collection elements:hasNext()(checks if there is a next element),next()(returns the next element), andremove()(removes the current element). -
The
for-eachconstruct (or enhanced for loop) in Java is syntactic sugar that simplifies iterating over collection elements. It works with any object implementing theIterableinterface or with arrays. Behind the scenes, the compiler transformsfor-eachinto code that usesIterator.
Example of using for-each with a list (which implements Iterable):
// Create a list of strings
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Use for-each to iterate
for (String name : names) {
System.out.println(name); // Print each element
}
Equivalent code using Iterator:
// Create a list of strings
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Get an iterator
Iterator<String> iterator = names.iterator();
// Iterate using the iterator
while (iterator.hasNext()) {
String name = iterator.next(); // Get the next element
System.out.println(name); // Print the element
}
Thus, for-each uses Iterator, obtained from Iterable, to simplify collection traversal syntax.