只需通过操作索引,您就可以以不同的顺序打印/访问数组元素。
尽管使用java8 lambda 表达式,下面的代码看起来会更整洁。
public class Matrix {
static interface Block {
void run(int array[][], int i, int j, int rows, int cols);
}
public static void main(String[] args) {
int array[][] = new int[6][5];
print(array, new Block() {
@Override
public void run(int array[][], int i, int j, int rows, int cols) {
System.out.printf("[%d,%d] ", i, j);
}
});
print(array, new Block() {
@Override
public void run(int array[][], int i, int j, int rows, int cols) {
System.out.printf("[%d,%d] ", j, i);
}
});
print(array, new Block() {
@Override
public void run(int array[][], int i, int j, int rows, int cols) {
System.out.printf("[%d,%d] ", rows - 1 - i, j);
}
});
print(array, new Block() {
@Override
public void run(int array[][], int i, int j, int rows, int cols) {
System.out.printf("[%d,%d] ", i, cols - 1 - j);
}
});
}
private static void print(int[][] array, Block block) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
block.run(array, i, j, array.length, array[i].length);
}
System.out.println();
}
System.out.println("------------------------");
}
}
输出
[0,0] [0,1] [0,2] [0,3] [0,4]
[1,0] [1,1] [1,2] [1,3] [1,4]
[2,0] [2,1] [2,2] [2,3] [2,4]
[3,0] [3,1] [3,2] [3,3] [3,4]
[4,0] [4,1] [4,2] [4,3] [4,4]
[5,0] [5,1] [5,2] [5,3] [5,4]
------------------------
[0,0] [1,0] [2,0] [3,0] [4,0]
[0,1] [1,1] [2,1] [3,1] [4,1]
[0,2] [1,2] [2,2] [3,2] [4,2]
[0,3] [1,3] [2,3] [3,3] [4,3]
[0,4] [1,4] [2,4] [3,4] [4,4]
[0,5] [1,5] [2,5] [3,5] [4,5]
------------------------
[5,0] [5,1] [5,2] [5,3] [5,4]
[4,0] [4,1] [4,2] [4,3] [4,4]
[3,0] [3,1] [3,2] [3,3] [3,4]
[2,0] [2,1] [2,2] [2,3] [2,4]
[1,0] [1,1] [1,2] [1,3] [1,4]
[0,0] [0,1] [0,2] [0,3] [0,4]
------------------------
[0,4] [0,3] [0,2] [0,1] [0,0]
[1,4] [1,3] [1,2] [1,1] [1,0]
[2,4] [2,3] [2,2] [2,1] [2,0]
[3,4] [3,3] [3,2] [3,1] [3,0]
[4,4] [4,3] [4,2] [4,1] [4,0]
[5,4] [5,3] [5,2] [5,1] [5,0]
------------------------