Creating your own Iterable.

suggest change

To create your own Iterable, implement its methods. The only abstract method is iterator(). Iterator itself has two abstract methods, hasNext() and next(). Since Java 8, remove() is a default method that throws UnsupportedOperationException. You can return an iterator from a collection, or write one:

public 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() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                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 starts positioned before the first item. Each next() call advances it. hasNext() reports whether an item remains. next() throws NoSuchElementException when nothing remains. If the iterator walks a modifiable collection, remove() can delete the item most recently returned by next().

Feedback about page:

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



Table Of Contents