如何实现迭代器?

时间:2015-10-23 19:39:48

标签: java arrays list iterator

我的班级有问题,我无法解决。我想为我的Interval1类实现一个迭代器。这是我的代码:

public class Interval1 {
    private double first;
    private double last;
    private double step;
    private IntervalIterator e;

    public Interval1(double first, double last, double step,  IntervalIterator e) {
        //chequear los datos
        this.first = first;
        this.last = last;
        this.step = step;
        this.e = new IntervalIterator();
    }

    public  double at(int index) {
        checkIndex(index);
        return first + index*step;
    }

    private void checkIndex(int index) {
        if(index < 0 || index >= size())
            throw new IndexOutOfBoundsException("Invalid Index: " + index);
    }

    public int size() {
        return (int) ((last - first) / step);
    }

    public IntervalIterator e() {
        for (Double i : this)
            System.out.println(i);
        return e;
    }
}

这是我正在使用的课程IntervalIterator,这会在size()at中出现错误:

public class IntervalIterator implements Iterator<Double> {
    private int index = 0;
    private Double at;

    public boolean hasNext() {
        return index < size();
    }

    public Double next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return at(index++);
    }

    public void remove() {
        if (Interval1 <= 0) {
            return throw new UnsupportedOperationException("remove");
        } else {
            if (Interval1 >= 0) {
                //chekear el array e eliminarlo
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我使用java8流来返回Iterator<Double>

public class Interval
    implements Iterable<Double> {

    private final double first;
    private final double last;
    private final double step;
    private final long size;

    public Interval(double first, double last, double step) {
        this.first = first;
        this.last = last;
        this.step = step;
        this.size = (long) ((last - first) / step) + 1;
    }

    @Override
    public Iterator<Double> iterator() {
        return DoubleStream.iterate(this.first, n -> n + this.step)
            .limit(this.size)
            .iterator();
    }

    // TODO getters
}

我已将final修饰符添加到字段中,并使Interval类实现Iterable<Double>,以便可以迭代它。我还修复了size的计算(需要加1)。

我使用了DoubleStream.iterate() method,它接收种子和接收流的当前元素作为输入的函数,并返回以下元素(为此我添加了{{ 1}}到当前元素)。我还必须使用DoubleStream.limit() method,因为step生成的流是无限的。

用法:

DoubleStream.iterate()

以上代码生成以下输出:

Interval interval = new Interval(3.0, 9.0, 1.5);

for (double n : interval) {
    System.out.println(n);
}