簡體   English   中英

如何實現迭代器?

[英]How to implement an 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
            }
        }
    }
}

我將使用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計算(需要加一)。

我使用了DoubleStream.iterate()方法 ,該方法接收一個種子和一個函數,該函數接收流的當前元素作為輸入並返回以下元素(為此,我已將step添加到當前元素中)。 我還必須使用DoubleStream.limit()方法 ,因為DoubleStream.iterate()生成的流是無限的。

用法:

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

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

上面的代碼生成以下輸出:

3.0
4.5
6.0
7.5
9.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM