【问题标题】:How to implement custom Iterator for multidimensional array in Java?如何在 Java 中为多维数组实现自定义迭代器?
【发布时间】:2019-08-21 05:19:58
【问题描述】:

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

例如如果数组是{{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。

【问题讨论】:

  • 验证数组是否包含您认为它包含的内容。要么在调试器中查看它,要么使用其他迭代将其写入标准输出。另外,请查看 Iterator 的合同。如果在没有下一个元素时调用 next 方法,则应该抛出 NoSuchElementException。此外,为了稳健性和通用性,请考虑检查array[currentRow].length 而不是array[0].length
  • Arrays 类的 deepToString 方法将格式化二维数组以进行打印。 hasNext 还应该测试 currentColumn 值

标签: java arrays multidimensional-array iterator


【解决方案1】:

一种可能的解决方案:

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

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2015-05-26
    • 1970-01-01
    相关资源
    最近更新 更多