Creating your own Iterable.

Download java eBook


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> {

    public Iterator<Character> iterator() {
        return new Iterator<Character>() {
            char letter = 'a';

            public boolean hasNext() {
                return letter <= 'z';

            public Character next() {
                return letter++;

            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.


Contributors: 2
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook