As an example, here's an implementation of an "infinite" sequence of 64-bit integers.
package blog;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class Sequence
implements Iterable<long> {
private long value;
public Sequence(long start) {
value=start;
}
public Sequence() {
this(0L);
}
public Iterator<long> iterator() {
return new LazyIterator();
}
public List<long> take(int toTake) {
ArrayList<long> retVal =
new ArrayList<long>(toTake);
for(int i = 0; i < toTake; ++i) {
public boolean hasNext() {
/* Always return true, because this
sequence is "infinite" */
return true;
}
public Long next() {
// store where we are
long retVal = value;
// Move on to the next value
++value;
// auto-boxing will turn it into a Long
return retVal;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
This technique is also useful for parsing documents or in other situations where generating the entire list would either take too long or too much memory.
No comments:
Post a Comment