java - 如何在 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。
解决方案
一种可能的解决方案:
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();
}
推荐阅读
- r - R:将while循环转换为递归
- javascript - 是否可以从 GA 获取链接的当前访问次数?
- django - 如何在 djagno 管理面板中使模型属性可编辑
- php - 如何在电子邮件模板中添加“添加到日历”链接
- selenium - Chrome 71 force-device-scale-factor < 1 不工作
- c - 有人可以解释为什么 GMP mpz_sizeinbase 会返回 1 太大吗?
- qt - QT 使用另一个类的公共插槽
- c# - 仅更新 datagridview 中的一个单元格
- python-3.x - Outlook Web 挂钩订阅
- amazon-web-services - 使用云形成在 AWS EC2 实例中创建文件的最佳实践