public class ArrayTranspose {
public static void main(String[] args) {
// 三行四列的数组
int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
System.out.println("原数组:");
printArray(array);
// 四行三列的数组
int[][] newArray = transpose(array, array.length, array[0].length);
System.out.println("转置后:");
printArray(newArray);
}
private static int[][] transpose(int[][] array, int originRowLength, int originColLength) {
// 原来的数组的行数等于新数组的列数
// 原来的数组的列数等于新数组的行数
int[][] newArray = new int[originColLength][originRowLength];
// 以原数组的行数和列数为基础
for (int rowIndex = 0; rowIndex < originRowLength; rowIndex++) {
for (int colIndex = 0; colIndex < originColLength; colIndex++) {
// 行列转换:原来的行索引是新的列索引,原来的列索引是新的行索引
newArray[colIndex][rowIndex] = array[rowIndex][colIndex];
}
}
return newArray;
}
private static void printArray(int[][] newArray) {
for (int rowIndex = 0; rowIndex < newArray.length; rowIndex++) {
for (int colIndex = 0; colIndex < newArray[0].length; colIndex++) {
System.out.print(newArray[rowIndex][colIndex] + "\t");
}
System.out.println();
}
}
}