我是Java的初学者,我必须从Iterator<Iterator<Integer>>这样的东西接收值。例如,我们可能有:

{{1, 2}, {3, 4}, {5, 6}}


next()的结果应为1。如果我们再尝试一次next()-2,则-34,等等。就像一维一维地从1D数组中获取值,而从2D数组中获取值。我们不应该复制任何东西。所以,我在下面写了一些不好的代码:

public class IteratorNext {

    private Iterator<Iterator<Integer>> values = null;
    private Iterator<Integer> current;

    public IteratorNext(Iterator<Iterator<Integer>> iterator) {
        this.values = iterator;
    }

    public int next() throws NoSuchElementException {
        current = values.next();
        if (!current.hasNext()) {
            values.next();
        }
        if (!values.hasNext() && !current.hasNext()) {
            throw new NoSuchElementException("Reached end");
        }
        return current.next();
    }
}


该代码是不正确的,因为next()的结果是1,然后是3,然后是5,并且这里是异常。如何解决?

最佳答案

如果您使用的是Java-8,则可以利用flatMapToInt函数将2D数组熨平为1D数组(可以将array2d视为对2D数组的引用):

Arrays.stream(array2d).flatMapToInt(Arrays::stream).forEach(System.out::println);


如果您要坚持解决方案,则需要按以下方式修改next方法:

public int next() throws NoSuchElementException {
    int result = -1;
    //Are we already iterating one of the second dimensions?
    if(current!=null && current.hasNext()) {
        //get the next element from the second dimension.
        result =  current.next();
    } else if(values != null && values.hasNext()) {
        //get the next second dimension
        current = values.next();
        if (current.hasNext()) {
            //get the next element from the second dimension
            result =  current.next();
        }
    } else {
        //we have iterated all the second dimensions
        throw new NoSuchElementException("Reached end");
    }

    return result;

}

关于java - 使用Iterator遍历2D数组,就好像它是1D数组一样,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42038195/

10-12 22:38