This article describes the two-dimensional array transpose function implemented by Java programming. Share it for your reference, as follows:
/** * Implement transposition of two-dimensional arrays* @author HAN * */public class transposition_Arrays2D_ch6_4 { final static double PI=3.1415; public static void main(String[] args) { /*StaticTest st1=new StaticTest(); StaticTest st2=new StaticTest(); st1.method2("HAN");*/ /***** Define the two-dimensional array to be used for transposition**********/ int arr2D[][]={{1,2,3},{4,5,6},{7,8,9}}; /*****Construct the result new two-dimensional array is used to store transposed results********/ /*Define the result array variable, be careful to open up a memory first, otherwise it is just address passing, that is, the two array names actually point to the same piece of memory*/ //The construction of a two-dimensional array can be done as a dimension, not necessarily a matrix, that is, the length of each row is not necessarily the same int result_arr[][]=new int[arr2D.length][];//First realize the first dimension for(int i=0; i<arr2D.length;i++){ //The second dimension result_arr[i]=new int[arr2D[i].length]; }// int result_arr[][]=Arrays.copyOf(arr2D, arr2D.length); //The above command line does not work! /******Output a two-dimensional array for transpose*******/ for (int x[]:arr2D){ for(int e:x){ System.out.print(e+" "); } System.out.println(); } System.out.println(); /*********Element inversion*******/ for(int i=0 ; i<arr2D.length;i++){ for(int j=0; j<arr2D[i].length;j++){ result_arr[j][i]=arr2D[i][j]; //Transfer core} } /******Show the result in the result matrix******/ for (int x[]:result_arr){ for(int e:x){ System.out.print(e+" "); } System.out.println(); } }}//import java.util.Arrays;//public class transfer_Arrays2D {//// public static void main(String[] args) {// int arr2D[][]={{1,2,3},{4,5,6},{7,8,9}};// /*Define the result array variable, be sure to open up a memory first, // Otherwise, it's just address passing, that is, the two array names actually point to the same piece of memory*/// int result_arr[][]=new int[arr2D.length][];// for(int i=0 ; i<arr2D.length;i++){// result_arr[i]=new int[arr2D[i].length];// }/// // Invert the element// for(int i=0 ; i<arr2D.length;i++){// for(int j=0; j<arr2D[i].length;j++){// result_arr[j][i]=arr2D[i][j];// }// }/// // show the result in matrix// for (int x[]:result_arr){// for(int e:x){// System.out.print(e);// }// System.out.println();// }/// }//// }//// }//// }//// }Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.