从java中的二维数组中获取列 [英] get columns from two dimensional array in java

查看:321
本文介绍了从java中的二维数组中获取列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在二维数组中,我可以轻松获取行的数组,如何将列作为数组?我需要一个适用于对象的解决方案,而不仅仅是原语。谢谢

In a two dimensional array I can easily get the arrays for the rows, how can I get the columns as arrays too? I need a solution that works for objects too, not just primitives. Thanks

        int counter = 1;
    int[][] matrix = new int[9][9];

    for (int x = 0; x < matrix.length; x++) {
        for (int y = 0; y < matrix[0].length; y++) {
            matrix[x][y] = counter;
            System.out.print(counter + " ");
            counter++;
        }
        System.out.println();
    }

    for (int x = 0; x < matrix.length; x++) {
        int[] row = matrix[x];  
    }


推荐答案

没有out-of 方框,但你可以为此创建一个静态方法:

There's no "out-of-the-box" way, but you can create a static method for this:

public static Object[] getColumn(Object[][] array, int index){
    Object[] column = new Object[array[0].length]; // Here I assume a rectangular 2D array! 
    for(int i=0; i<column.length; i++){
       column[i] = array[i][index];
    }
    return column;
}

这篇关于从java中的二维数组中获取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆