To create your own Iterable as with any interface you just implement the abstract methods in the interface. For Iterable
there is only one which is called iterator()
. But its return type Iterator
is itself an interface with three abstract methods. You can return an iterator associated with some collection or create your own custom implementation:
public static class Alphabet implements Iterable<Character> {
@Override
public Iterator<Character> iterator() {
return new Iterator<Character>() {
char letter = 'a';
@Override
public boolean hasNext() {
return letter <= 'z';
}
@Override
public Character next() {
return letter++;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Doesn't make sense to remove a letter");
}
};
}
}
To use:
public static void main(String[] args) {
for(char c : new Alphabet()) {
System.out.println("c = " + c);
}
}
The new Iterator
should come with a state pointing to the first item, each call to next updates its state to point to the next one. The hasNext()
checks to see if the iterator is at the end. If the iterator were connected to a modifiable collection then the iterator's optional remove()
method might be implemented to remove the item currently pointed to from the underlying collection.