Junior — Middle
Explain the differences between the interfaces Iterator, Comparator, and Iterable in Java.
sobes.tech AI
Answer from AI
Iterator is an interface that provides methods for sequentially traversing a collection (for example, hasNext(), next(), remove()). It allows obtaining elements one by one without revealing the internal structure of the collection.
Iterable is an interface that indicates an object can be traversed with an iterator. It contains one method iterator(), which returns an Iterator object. Thanks to this, the object can be used in a for-each loop.
Comparator is an interface for defining the order of sorting objects. It contains the method compare(T o1, T o2), which determines which of the two objects should come first. It is used for sorting collections based on custom criteria.
Example:
List<String> list = Arrays.asList("apple", "banana", "cherry");
// Iterable allows using for-each
for (String fruit : list) {
System.out.println(fruit);
}
// Iterator for manual traversal
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// Comparator for sorting by string length
Comparator<String> byLength = (s1, s2) -> Integer.compare(s1.length(), s2.length());
Collections.sort(list, byLength);
System.out.println(list); // [apple, cherry, banana]