Junior — Middle
What is the Iterable interface in Java and what are its advantages and disadvantages?
sobes.tech AI
Answer from AI
The Iterable<T> interface in Java represents a collection of objects that can be iterated over using a for-each loop. It defines a single method iterator(), which returns an Iterator<T> object that allows sequential access to the elements of the collection.
Advantages:
- Allows the use of convenient
for-eachsyntax for traversing elements. - Universal: many collections and data structures implement
Iterable, ensuring compatibility. - Provides an abstraction of iteration, hiding implementation details.
Disadvantages:
- Does not support random access to elements (e.g., by index).
- The iterator may be single-use; after a full traversal, it cannot be reused without creating a new one.
- Does not guarantee thread safety if the collection is modified during iteration.
Example of usage:
List<String> list = Arrays.asList("a", "b", "c");
for (String s : list) {
System.out.println(s);
}