集册 Java实例教程 转置二维阵列

转置二维阵列

欢马劈雪     最近更新时间:2020-01-02 10:19:05

537
转置二维阵列


//package com.nowjava;/*来自 时代Java公众号 - N o w J a  v a . c o m*/

import java.lang.reflect.Array;


public class Main {

    public static double[][] transpose(double[][] array) {

        if (array == null || array.length == 0 || array[0].length == 0) {

            throw new RuntimeException("Null or empty array");

        }


        double[][] transposed = new double[array[0].length][array.length];


        for (int i = 0; i < transposed.length; i++) {

            for (int j = 0; j < array.length; j++) {

                transposed[i][j] = array[j][i];

            }

        }


        return transposed;
        /*来自 
         nowjava - 时  代  Java*/

    }


    public static int[][] transpose(int[][] array) {

        if (array == null || array.length == 0 || array[0].length == 0) {

            throw new RuntimeException("Null or empty array");

        }


        int[][] transposed = new int[array[0].length][array.length];


        for (int i = 0; i < transposed.length; i++) {

            for (int j = 0; j < array.length; j++) {

                transposed[i][j] = array[j][i];

            }

        }


        return transposed;

    }


    public static Object[][] transpose(Object[][] array) {

        if (array == null || array.length == 0 || array[0].length == 0) {

            throw new RuntimeException("Null or empty array");

        }


        Object[][] transposed = (Object[][]) Array.newInstance(array[0]

                .getClass().getComponentType(),
展开阅读全文