[英]How to implement custom Iterator for multidimensional array in Java?
我目前正在嘗試為二維數組設置自定義 Iterator 方法。
例如,如果數組是{{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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.