Java 获取二维数组的行数和列数而不对其进行迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21363104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:18:56  来源:igfitidea点击:

getting rows and columns count of a 2D array without iterating on it

javamatrixmultidimensional-array

提问by Aniket Thakur

I have a function which takes 2D array. I am wondering if there is anyway to get rows and columns of the 2D array without having to iterate on it. Method signature is not to be changes.

我有一个接受二维数组的函数。我想知道是否有办法获得二维数组的行和列而不必对其进行迭代。方法签名是不可更改的。

Function is inside the ninetyDegRotatorclass.

函数在ninetyDegRotator类里面。

public static int [][] rotate(int [][] matrix){

    int [][] rotatedMatrix = new int[4][4];//need actual row n col count here
    return rotatedMatrix; //logic

}

And main code is

主要代码是

public static void main(String args[]){

    int [][] matrix = new int[][]{
            {1,2,3,4},
            {5,6,7,8},
            {9,0,1,2},
            {3,4,5,6}
    };

    System.out.println("length is " + matrix.length);
    int [][] rotatedMatrix = ninetyDegRotator.rotate(matrix);
} 

Also matrix.lengthgives me 4. So I guess it is number of rows that it gives meaning number of references in 1D array which themselves contain arrays. So is there a way to get the count without iterating?

matrix.length给了我4。所以我猜它是行数,它给出了本身包含数组的一维数组中的引用数。那么有没有办法在不迭代的情况下获得计数?

采纳答案by Alnitak

If it's guaranteed that each row has the same length, just use:

如果保证每行具有相同的长度,只需使用:

int rows = matrix.length;
int cols = matrix[0].length;  // assuming rows >= 1

(In mathematics this is of course guaranteed, but it's quite possible in most languages to have an array of arrays, where the inner arrays are notall the same length).

(在数学中,这当然是有保证的,但在大多数语言中很可能有一个数组数组,其中内部数组的长度并不完全相同)。

回答by Nikhil Kumar

int row = mat.length;
int col= mat[0].length;

Mostly in array all row has same length. So above solution will work almost every time.

大多数情况下,所有行都在数组中具有相同的长度。所以上述解决方案几乎每次都有效。