这是我为算术级数编写的 implements Iterable<Integer> 类(从 startstop 的步骤 step )

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);
    }
}

有没有办法实现更优雅的 iterator() ?我不喜欢空检查和 Integer 的使用(替代方法是额外的标志 boolean firstTime ),这似乎是错误的。

最佳答案

return new AbstractIterator<Integer>() {
  int next = getStart();

  @Override protected Integer computeNext() {
    if (isBeyondEnd(next)) {
      return endOfData();
    }
    Integer result = next;
    next = next + getStep();
    return result;
  }
};

如果您愿意,您可以将其实现为不可变的 List<Integer> 。如果您扩展 AbstractList,那么 Iterator 会为您处理。实际上,我认为 AbstractList 真的是最好的方法。整个类(class)看起来像这样(我没有检查它是否在所有情况下都能正常工作):
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;
  }
}

关于java - 为算术级数制作一个惰性迭代器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5795948/

10-11 02:38