transpose two dimensional array - Java Collection Framework

Java examples for Collection Framework:Array Dimension

Description

transpose two dimensional array

Demo Code


//package com.java2s;
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");
        }/*from w ww .  j a v a  2s .c  o  m*/

        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;
    }

    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(), 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;
    }
}

Related Tutorials