首页 > 解决方案 > 如何在 Java 中为多维数组实现自定义迭代器?

问题描述

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

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

我的想法是这样的:

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。

标签: javaarraysmultidimensional-arrayiterator

解决方案


一种可能的解决方案:

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();
}

推荐阅读