Creating your own Iterable.

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Iterator and Iterable:
* Creating your own Iterable.

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
38 Iterator and Iterable
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap