How to iterate over each element in a jagged array?

前端 未结 3 2077
温柔的废话
温柔的废话 2020-12-22 14:38

I have one 2 dimensional array, so an array of arrays. The arrays of the arrays DONT have the same lengths. Here an example:

double[][] multi = new double[][         


        
相关标签:
3条回答
  • 2020-12-22 14:51

    You can do it like this to iterate the whole array column-wise:

    // Get the maximum number of columns among all rows.
    int maximumColumns = 0;
    for (double[] row : multi) {
        if (row.length > maximumColumns) {
            maximumColumns = row.length;
        }
    }
    
    for (int column = 0; column < maximumColumns ; column++) {
        for (int row = 0; row < multi.length; row++) {
            if (column >= multi[row].length) {
                // There is no value for this column.
            } else {
                // Do stuff here with multi[row][column].
            }
        }
    }
    

    For a specific column that exists in all rows do this:

    int columnToIterate = // Your column.
    for (int row = 0; row < multi.length; row++) {
        if (columnToIterate < multi[row].length) {
            // Do stuff here with multi[row][columnToIterate].
        }
    }
    
    0 讨论(0)
  • 2020-12-22 15:01

    2D arrays are array of arrays... So one can iterate as:

       for (double[] row: multi) {
           for(double value: row) {
           }
       }
    
    0 讨论(0)
  • 2020-12-22 15:01

    Do this:

    for(int i=0; i<multi.length; i++) {
                for(int j=0; j<multi[i].length; j++) {
                    System.out.println("Values at multi["+i+"]["+j+"] is "+multi[i][j]);
                }
            }
    
    0 讨论(0)
提交回复
热议问题