获取Java中的二维数组的数组长度 [英] Getting the array length of a 2D array in Java

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

问题描述

我需要得到一个二维数组的长度为行和列两者。我已经成功地做​​到了这一点,用下面的code:

I need to get the length of a 2D array for both the row and column. I’ve successfully done this, using the following code:

public class MyClass {

 public static void main(String args[])
    {
  int[][] test; 
  test = new int[5][10];

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

  System.out.println(row);
  System.out.println(col);
    }
}

这打印出5,10符合市场预期。

This prints out 5, 10 as expected.

现在来看看这一行:

  int col = test[0].length;

请注意,我实际上是引用一个特定的行,为了得到列的长度。对我来说,这似乎令人难以置信的丑陋。此外,如果该阵列被定义为:

Notice that I actually have to reference a particular row, in order to get the column length. To me, this seems incredibly ugly. Additionally, if the array was defined as:

test = new int[0][10];

然后试图获得的长度时,code会失败。是否有不同的(更智能)的方式来做到这一点?

Then the code would fail when trying to get the length. Is there a different (more intelligent) way to do this?

推荐答案

考虑

public static void main(String[] args) {

    int[][] foo = new int[][] {
        new int[] { 1, 2, 3 },
        new int[] { 1, 2, 3, 4},
    };

    System.out.println(foo.length); //2
    System.out.println(foo[0].length); //3
    System.out.println(foo[1].length); //4
}

列长度每行不同。如果你被一个固定大小的二维数组支持的一些数据,然后提供给干将固定值的包装类。

Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.

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

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