/ programming

Infinity

While in a heavy debugging session earlier today, I had a (totally unrelated) realization that it is in fact very easy to create a generator in
Java. Use it as you see fit :-)

/**
 * Generate integers. There are three optional parameters as follows:
 * 1. begin (= 0)
 * 2. end   (= infinitely)
 * 3. step  (= 1)
 *
 * Example usage:
 * for (Integer i : newIntegerGenerator(10, 20, 2)) {
 *    // ...
 * }
 */
public static Iterable<Integer> newIntegerGenerator(final int ... params) {
    return new Iterable<Integer>() {
        @Override
        public Iterator<Integer> iterator() {
            return new Iterator<Integer>() {
                private int current = params.length > 0 ? params[0] : 0;
                
                @Override
                public Integer next() {
                    int result = current;
                    current += params.length > 2 ? params[2] : 1;
                    return result;
                }
                    
                @Override
                public boolean hasNext() {
                    return params.length < 2 || current <= params[1];
                }
            };
        }
    };
}