Java – making a lazy iterator for arithmetic series?
•
Java
This is a class I wrote to implement iteratable < integer > Arithmetic series (from step start to stop)
package com.example.test; import java.util.Iterator; import com.google.common.collect.AbstractIterator; public class ArithmeticSeries implements Iterable<Integer> { final private int start,step,stop; public int getStart() { return this.start; } public int getStep() { return this.step; } public int getStop() { return this.stop; } public ArithmeticSeries(int start,int step,int stop) { this.start = start; this.step = step; this.stop = stop; } @Override public Iterator<Integer> iterator() { return new AbstractIterator<Integer>() { private Integer n = null; @Override protected Integer computeNext() { int next; if (this.n == null) { next = getStart(); } else { next = this.n + getStep(); if ((getStep() > 0 && next > getStop()) || (getStep() < 0 && next < getStop())) return endOfData(); } this.n = next; return next; } }; } @Override public String toString() { return getStart()+":"+getStep()+":"+getStop(); } public static void main(String[] args) { Iterable<Integer> range = new ArithmeticSeries(100,-1,80); System.out.println(range); for (int i : range) System.out.println(i); } }
Is there any way to implement a more elegant iterator ()? I don't like null checking and using integer (substitution will be an additional flag Boolean firsttime), it seems wrong
Solution
return new AbstractIterator<Integer>() {
return new AbstractIterator<Integer>() { int next = getStart(); @Override protected Integer computeNext() { if (isBeyondEnd(next)) { return endOfData(); } Integer result = next; next = next + getStep(); return result; } };
If you like, you can implement it as an immutable list < integer > If you extend abstractlist, iterator will handle it for you In fact, I think abstractlist is really the best way The whole class looks like this (I didn't check that it works properly in all cases):
public class ArithmeticSeries extends AbstractList<Integer> { private final int start; private final int step; private final int size; public ArithmeticSeries(int start,int end,int step) { this.start = start; this.step = (start < end) ? step : -step; this.size = (end - start) / this.step + 1; } @Override public Integer get(int index) { return start + step * index; } @Override public int size() { return size; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码