Junior
What is the Iterable interface in Java?
sobes.tech AI
Answer from AI
Iterable<T> is an interface in Java that allows objects to become "iterable," meaning they can be traversed using a for-each loop. It indicates that a class implementing this interface can return an Iterator.
Key points:
- Contains a single abstract method
iterator(), which returns an object of typeIterator<T>. - Supports the enhanced for loop (
for-each). - Is a parent interface of
Collection. All implementations ofCollection(such asArrayList,HashSet,LinkedList) implementIterableand are therefore iterable.
Example usage:
// Example of a class implementing Iterable
import java.util.Iterator;
class MyIterableCollection<T> implements Iterable<T> {
private T[] items;
private int size;
// constructor and add methods...
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
// Inner class for the iterator
private class MyIterator implements Iterator<T> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < size;
}
@Override
public T next() {
return items[currentIndex++];
}
}
}
// Usage in a for-each loop
class Main {
public static void main(String[] args) {
MyIterableCollection<String> collection = new MyIterableCollection<>();
// Adding elements...
for (String item : collection) {
System.out.println(item); // Can iterate thanks to Iterable
}
}
}