我如何覆盖锯齿状数组java的next()?

时间:2018-09-17 12:59:07

标签: java iterator next jagged-arrays

我有一个锯齿状的数组。 如何覆盖next(),以便逐步了解其元素?

3 个答案:

答案 0 :(得分:1)

这可能是对您问题的错误答案。在这种情况下,我将其删除,但是也许您可以将其用于想要实现的目标:

int[][] it = {{1,2}, {3,4,5}};

OfInt iterator = Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).iterator();
iterator.forEachRemaining((IntConsumer) System.out::print);

串流锯齿状数组,将其平面映射为一个IntStream,然后使用它进行所需的操作。在此示例中,我获取了迭代器,但您可能只想要:

Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).forEach((IntConsumer) System.out::print); 

forEach中,您可以执行所需的操作,或使用IntStream的其他方法

答案 1 :(得分:0)

谢谢大家的回答,我在俄语stackoverflow中找到了答案: https://ru.stackoverflow.com/questions/867881/java-iterator-%D0%B4%D0%BB%D1%8F-%D0%BC%D0%BD%D0%BE%D0%B3%D0%BE%D0%BC%D0%B5%D1%80%D0%BD%D0%BE%D0%B3%D0%BE-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%D0%B0

公共类IteratorFor2DArray实现Iterator {

private int size;
private int i = 0;
private int j = 0;
private int[][] values = new int[i][j];
private int position = 0;

public IteratorFor2DArray(int[][] values) {
    this.values = values;
    this.size = countOfElements(values);
}

private int countOfElements(int[][] values) {
    int count = 0;
    for (int[] row : values) {
        count += row.length;
    }
    return count;
}

@Override
public boolean hasNext() {
    return position < size;
}

@Override
public Integer next() {
    if (position >= size) {
        throw new NoSuchElementException();
    }
    int element = values[i][j];
    position++;
    j++;
    while (i < values.length && j >= values[i].length) {
        j = 0;
        i++;
    }
    return element;
}

}

答案 2 :(得分:0)

我还找到了另一种方法:

public class IteratorFor2DArray implements Iterator {

    private int[][] data;
    private int i, j;

    public IteratorFor2DArray(int[][] data) {
        this.data = data;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        int element = data[i][j];
        j++;
        while (i < data.length && j >= data[i].length) {
            j = 0;
            i++;
        }
        return element;
    }

    @Override
    public boolean hasNext() {
        return (i < data.length && j < data[i].length);
    }
}