如何遍历锯齿数组中的每个元素? [英] How to iterate over each element in a jagged array?
本文介绍了如何遍历锯齿数组中的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二维数组,所以是一个数组数组.阵列DONT的阵列具有相同的长度. 这里是一个例子:
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 }
};
如何遍历各列? (例如:10 1.1 1.2 1
)
How can I loop through the columns? (Like: 10 1.1 1.2 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].
}
}
这篇关于如何遍历锯齿数组中的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文