Sobes.tech
Junior — Middle

In what cases is it recommended to use the Iterable interface in your development?

sobes.tech AI

Answer from AI

The Iterable interface in Android (Java/Kotlin) is recommended to be used when you need to make an object or collection iterable, that is, capable of returning an iterator for sequential traversal of elements.

This is useful if you create your own collections or data structures and want them to be usable in for-each loops.

Example of usage in Java:

public class MyCollection implements Iterable<String> {
    private List<String> items = new ArrayList<>();

    public void add(String item) {
        items.add(item);
    }

    @Override
    public Iterator<String> iterator() {
        return items.iterator();
    }
}

// Usage:
MyCollection collection = new MyCollection();
collection.add("Example");
for (String item : collection) {
    System.out.println(item);
}