Sobes.tech
Junior — Middle

Can you explain the purpose and working principle of the Iterable interface in programming?

sobes.tech AI

Answer from AI

The Iterable interface in programming (for example, in Java) defines an object that can be traversed using a for-each loop or an iterator. Its main purpose is to provide a way to access the elements of a collection sequentially without revealing its internal structure.

Working principle:

  • The interface contains a method iterator(), which returns an object of type Iterator.
  • The iterator allows sequential access to the collection's elements through the methods hasNext() and next().

Example implementation:

import java.util.Iterator;

class MyCollection implements Iterable<String> {
    private String[] data = {"A", "B", "C"};

    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int index = 0;

            public boolean hasNext() {
                return index < data.length;
            }

            public String next() {
                return data[index++];
            }
        };
    }
}

// Usage
MyCollection coll = new MyCollection();
for (String s : coll) {
    System.out.println(s);
}

Thus, Iterable simplifies element traversal and makes the code more readable and versatile.

Can you explain the purpose and working principle of… - sobes.tech