I have implemented a MatrixIt class to traverse a 2D array. Is it possible to make the code clearer and shorter?

public class MatrixIt implements Iterator<Integer> {
    private final int[][] data;
    private int row = 0;
    private int column = 0;

    public MatrixIt(int[][] data) {
        this.data = data;

    public boolean hasNext() {
        while (row < data.length && data[row].length == column) {
            column = 0;
        return row < data.length;

    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        return data[row][column++];
  • \$\begingroup\$ The while in your hasNext method could probably be changed to a simple if statement \$\endgroup\$ Jul 7 '21 at 19:08
  • 1
    \$\begingroup\$ How do you expect your hasNext() and next() methods to behave? How do you define traversal in context of a matrix? \$\endgroup\$
    – Kitswas
    Jul 8 '21 at 7:09

Interestingly, the thing that most facilitates a simple row-wise iterator is to arrange the storage in the same format that we'll iterate.

Instead of having an array of references to per-row arrays, representing a matrix by a single linear array is a good choice: faster to create, and with better memory locality:

public class Matrix {
    private int[] data;
    int width;
    int height;

    int get(int x, int y) {
        return data[y * width + x];

    void set(int x, int y, int value) {
        data[y * width + x] = value;

Then the iterator can be a simple (linear) iterator over the data.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.