我目前正在尝试为二维数组设置自定义Iterator方法。

例如。如果数组是{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},则每次调用1、2、3、4、5、6、7、8、9时,next()方法应依次返回。

我的想法是这样的:

public Iterator<Type> iterator() {
    return new Iterator<Type>() {
        private int currentRow = 0;
        private int currentColumn = 0;

        public boolean hasNext() {
            return currentRow < array.length;
        }

        public Type next() {
            if(currentColumn + 1 == array[0].length){
                currentColumn = 0;
                currentRow ++;
            }
            return array[currentRow][currentColumn++];
        }
    }
}


但是它不会以正确的顺序输出项目,有时甚至会返回null。

最佳答案

一种可能的解决方案:

public Iterator<Type> iterator() {
    return new Iterator<Type>() {
        private int currentRow = 0;
        private int currentColumn = 0;

        public boolean hasNext() {
            if (currentRow + 1 == array.length) {
                return currentColumn < array[currentRow].length;
            }
            return currentRow < array.length;
        }

        public Type next() {
            if (currentColumn == array[currentRow].length) {
                currentColumn = 0;
                currentRow++;
            }
            if (currentRow == array.length -1 && currentColumn == array[currentRow].length - 1) {
                throw new NoSuchElementException();
            }
            return array[currentRow][currentColumn++];
        }
    };
}


另外,您可以使用Java Streams:

public Iterator<Type> iterator() {
    return Arrays.stream(array)
            .flatMap(Arrays::stream)
            .iterator();
}


对于整数,它看起来像这样:

public Iterator<Integer> iterator() {
    return Arrays.stream(array)
            .map(Arrays::stream)
            .flatMap(IntStream::boxed)
            .iterator();
}

07-24 09:47
查看更多