How to iterate over each element in a jagged array?

血红的双手。 提交于 2020-12-23 18:30:46

问题


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[][] { 
  { 10, 20, 30, 40, 50 }, 
  { 1.1, 2.2, 3.3, 4.4 }, 
  { 1.2, 3.2 },
  { 1, 2, 3, 4, 5, 6, 7, 8, 9 } 
};

How can I loop through the columns? (Like: 10 1.1 1.2 1)


回答1:


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].
    }
}



回答2:


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

   for (double[] row: multi) {
       for(double value: row) {
       }
   }



回答3:


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]);
            }
        }


来源:https://stackoverflow.com/questions/40961513/how-to-iterate-over-each-element-in-a-jagged-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!