我是一个Java初学者,我必须从Iterator<Iterator<Integer>>
这样的东西中接收数值。例如,我们可能有:通过二维数组迭代,就好像它是一维数组一样使用迭代器
{{1, 2}, {3, 4}, {5, 6}}
的next()
结果应该是1
。如果我们再试一次next()
- 2
,则 - 3
,4
等等。就像从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'?然后有一个更简单的方法来做到这一点。 – CKing