Over a million developers have joined DZone.

Handy Iterable For A Range Of Integers

Looping a specific number of times produces code a bit too verbose in Java.  The JDK5 enhanced for statement is a handy improvement, but you still have to fall back to the traditional for statement if you want to repeat a loop, say, 10 times.

Not with this implementation of Iterable.  You can use it like this:

for (int i : new Range(100))
    System.out.printf("I have said this %d times. Read dzone.com!%n", i);

class Range implements Iterable {
    private final Integer stop;
    public Range(int stop) {
        this.stop = stop;

    public Iterator iterator() {
        return new Iterator() {
            private Integer counter = 0;

            public boolean hasNext() {
                return (counter != stop);

            public Integer next() {
                if (counter == stop)
                    throw new NoSuchElementException();
                return ++counter;

            public void remove() {

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}