Whenever I had to deal with matrices(bi-dimensional array), I had to struggle a bit how to iterate them.. you know the classic imbricated for
loop from school …
for(int i=0; i<matrix.len; i++)
for(int j=0;... j++)
But here is my mental model which helps me better understand matrix iteration.
I think about a matrix is just like a ‘normal'(one-dimensional) array, whose elements are arrays themselves.
so in String[][] myMatrix
the first part – String[]
is the main array, and the second part []
refers to the array within(of) the main array
So, matrix[2][0]
means – I want to access in the matrix the element at index 2(circled in red) – which gives me an array of String: String[3] subArray
and from that row/subArray we get the element at index 0
How to iterate?
I) From Up to Down -> go to the i row
a[i] returns us the row(subArray) at index i
II) From Left to Right, -> in that row, go to the j element
a[][j] once we’re on the desired row, to j iterator returns us the desire element from the given row
for (int rowIdx = 0; rowIdx < matrix.length; rowIdx++) {
T[] oneLine = matrix[rowIdx];
for (int colIdx = 0; colIdx < oneLine.length; colIdx++) {
oneLine[colIdx] = valProducer.apply(new RowColPair(rowIdx, colIdx));
}
}