具有相同长度的列表
public static void main(String[] args) {
String[][] values = new String[][] {
{ "1_1", "1_2", "1_3" },
{ "2_1", "2_2", "2_3" },
{ "3_1", "3_2", "3_3" }
};
for (int count = 0; count < values.length * values[0].length; count++) {
System.out.println(values[count % values.length][count / values[0].length]);
}
}
表达式:
count % values.length
在所有行之间旋转,而表达式:
count / values[0].length
在多次迭代后增加一。
不同长度的列表
public static void main(String[] args) {
String[][] values = new String[][] {
{ "1_1", "1_2", "1_3" },
{ "2_1", "2_2" },
{ "3_1", "3_2", "3_3", "3_4" }
};
for (int count = 0, maxLen = 0;; count++) {
int row = count % values.length;
int col = count / values[0].length;
maxLen = Math.max(values[row].length, maxLen);
if (values[row].length > col) {
System.out.println(values[row][col]);
} else if (row + 1 == values.length && col >= maxLen) break;
}
}
为具有相同长度的列表提供的解决方案的差异是:
- 仅当当前列表定义了计算列时才获取值。
- 在迭代值时收集所有列表的最大长度。
- 如果不存在定义当前计算列的列表,则停止。