Last active
August 29, 2015 13:57
-
-
Save kjaquier/9566940 to your computer and use it in GitHub Desktop.
How to create a simple iterator in Java with just one method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ClosureIterator { | |
private static interface Iterator<T> { | |
T next(); | |
} | |
private static class Container<T> { | |
private T value; | |
public Container(T value) { | |
setValue(value); | |
} | |
public T getValue() { | |
return value; | |
} | |
public void setValue(T value) { | |
this.value = value; | |
} | |
} | |
private static Iterator<Integer> evenGenerator() { | |
final Container<Integer> i = new Container<>(0); | |
return new Iterator<Integer>() { | |
@Override | |
public Integer next() { | |
int tmp = i.getValue(); | |
i.setValue(i.getValue() + 2); | |
return tmp; | |
} | |
}; | |
} | |
public static void main(String[] args) { | |
Iterator<Integer> it = evenGenerator(); | |
System.out.println(it.next()); // 0 | |
System.out.println(it.next()); // 2 | |
System.out.println(it.next()); // 4 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment