I'm currently trying to set up a custom Iterator method for a 2-dimensional array.
E.g. if the array is {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} the next()-method should return successively with every call 1, 2, 3, 4, 5, 6, 7, 8, 9.
My idea was something like this:
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++];
}
}
}
But it doesn't output the items in the right order and sometimes it even returns null.
NoSuchElementExceptionif it's called when there is no next element. Also, for robustness and generality, consider checkingarray[currentRow].lengthrather thanarray[0].length.