猿问

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

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


蛊毒传说
浏览 198回答 3
3回答

四季花海

这可能是您问题的错误答案。在这种情况下,我会删除它,但也许您可以将它用于您想要实现的目标: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

绝地无双

公共类 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) {&nbsp; &nbsp; this.values = values;&nbsp; &nbsp; this.size = countOfElements(values);}private int countOfElements(int[][] values) {&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for (int[] row : values) {&nbsp; &nbsp; &nbsp; &nbsp; count += row.length;&nbsp; &nbsp; }&nbsp; &nbsp; return count;}@Overridepublic boolean hasNext() {&nbsp; &nbsp; return position < size;}@Overridepublic Integer next() {&nbsp; &nbsp; if (position >= size) {&nbsp; &nbsp; &nbsp; &nbsp; throw new NoSuchElementException();&nbsp; &nbsp; }&nbsp; &nbsp; int element = values[i][j];&nbsp; &nbsp; position++;&nbsp; &nbsp; j++;&nbsp; &nbsp; while (i < values.length && j >= values[i].length) {&nbsp; &nbsp; &nbsp; &nbsp; j = 0;&nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; }&nbsp; &nbsp; return element;}}

largeQ

我还找到了另一种方法:public class IteratorFor2DArray implements Iterator {&nbsp; &nbsp; private int[][] data;&nbsp; &nbsp; private int i, j;&nbsp; &nbsp; public IteratorFor2DArray(int[][] data) {&nbsp; &nbsp; &nbsp; &nbsp; this.data = data;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public Integer next() {&nbsp; &nbsp; &nbsp; &nbsp; if (!hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new NoSuchElementException();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; int element = data[i][j];&nbsp; &nbsp; &nbsp; &nbsp; j++;&nbsp; &nbsp; &nbsp; &nbsp; while (i < data.length && j >= data[i].length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return element;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public boolean hasNext() {&nbsp; &nbsp; &nbsp; &nbsp; return (i < data.length && j < data[i].length);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Python
我要回答