在Java中获取二维数组的数组长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4000169/
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-14 08:09:39  来源:igfitidea点击:

Getting the array length of a 2D array in Java

javaarraysmultidimensional-array

提问by user432209

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

This prints out 5, 10 as expected.

这会按预期打印出 5, 10。

Now take a look at this line:

现在看看这一行:

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

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

然后在尝试获取长度时代码会失败。有没有不同(更智能)的方法来做到这一点?

采纳答案by NG.

Consider

考虑

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.

每行的列长度不同。如果您通过固定大小的 2D 数组支持某些数据,则为包装类中的固定值提供 getter。

回答by robert_x44

Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:

Java 允许您创建“参差不齐的数组”,其中每个“行”具有不同的长度。如果你知道你有一个方形数组,你可以使用修改过的代码来防止像这样的空数组:

if (row > 0) col = test[0].length;

回答by kaliatech

There's not a cleaner way at the language level because not all multidimensional arrays are rectangular. Sometimes jagged (differing column lengths) arrays are necessary.

在语言级别没有更简洁的方法,因为并非所有多维数组都是矩形的。有时需要锯齿状(不同的列长度)数组。

You could easy create your own class to abstract the functionality you need.

您可以轻松创建自己的类来抽象您需要的功能。

If you aren't limited to arrays, then perhaps some of the various collection classes would work as well, like a Multimap.

如果您不限于数组,那么也许各种集合类中的一些也可以工作,例如Multimap

回答by Ishtar

A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.

二维数组不是矩形网格。或者也许更好,Java 中没有二维数组这样的东西。

import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    int[][] test; 
    test = new int[5][];//'2D array'
    for (int i=0;i<test.length;i++)
      test[i] = new int[i];

    System.out.println(Arrays.deepToString(test));

    Object[] test2; 
    test2 = new Object[5];//array of objects
    for (int i=0;i<test2.length;i++)
      test2[i] = new int[i];//array is a object too

    System.out.println(Arrays.deepToString(test2));
  }
}

Outputs

输出

[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]

The arrays testand test2are (more or less) the same.

数组testtest2(或多或少)相同。

回答by Pampanagouda Karmanchi

Try this following program for 2d array in java:

在 Java 中为 2d 数组尝试以下程序:

public class ArrayTwo2 {
    public static void main(String[] args) throws  IOException,NumberFormatException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[][] a;
        int sum=0;
        a=new int[3][2];
        System.out.println("Enter array with 5 elements");
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            System.out.print(a[i][j]+"  ");
            sum=sum+a[i][j];
            }
        System.out.println();   
        //System.out.println("Array Sum: "+sum);
        sum=0;
        }
    }
}

回答by peter

public class Array_2D {
int arr[][];
public Array_2D() {
    Random r=new Random(10);
     arr = new int[5][10];
     for(int i=0;i<5;i++)
     {
         for(int j=0;j<10;j++)
         {
             arr[i][j]=(int)r.nextInt(10);
         }
     }
 }
  public void display()
  {
         for(int i=0;i<5;i++)

         {
             for(int j=0;j<10;j++)
             {
                 System.out.print(arr[i][j]+" "); 
             }
             System.out.println("");
         }
   }
     public static void main(String[] args) {
     Array_2D s=new Array_2D();
     s.display();
   }  
  }

回答by peter

If you have this array:

如果你有这个数组:

String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
                       {{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};

You can do this:

你可以这样做:

example.length;

= 2

= 2

example[0].length;

= 2

= 2

example[1].length;

= 2

= 2

example[0][1].length;

= 3

= 3

example[1][0].length;

= 4

= 4

回答by RobynVG

import java.util.Arrays;

public class Main {

    public static void main(String[] args) 
    {

        double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000}};

        int [][] removeRow = { {0}, {1}, {3}, {4}, };

        double[][] newTest = new double[test.length - removeRow.length][test[0].length];

        for (int i = 0, j = 0, k = 0; i < test.length; i++) {
            if (j < removeRow.length) {
                if (i == removeRow[j][0]) {
                    j++;
                    continue;
                }
            }
            newTest[k][0] = test[i][0];
            k++;
        }

        System.out.println(Arrays.deepToString(newTest));   
    }
}

回答by gocode

It was really hard to remember that

真的很难记住

    int numberOfColumns = arr.length;
    int numberOfRows = arr[0].length;

Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:

让我们了解为什么会这样,以及当我们遇到数组问题时如何解决这个问题。从下面的代码我们可以看到行 = 4 和列 = 3:

    int[][] arr = { {1, 1, 1, 1}, 

                    {2, 2, 2, 2}, 

                    {3, 3, 3, 3} };

arrhas multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of columns. To get the number of rows, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of rows by accessing the first array then its length. The other one (arr.length) is for the columns.

arr里面有多个数组,这些数组可以垂直排列,得到列数。要获得行数,我们需要访问第一个数组并考虑其长度。在这种情况下,我们访问 [1, 1, 1, 1],因此行数 = 4。当您遇到看不到数组的问题时,您可以将数组可视化为一个矩形n X m 维并得出结论,我们可以通过访问第一个数组然后访问其长度来获得行数。另一个 ( arr.length) 用于列。

回答by asdfgghjkll

.length = number of rows / column length

.length = 行数/列长

[0].length = number of columns / row length

[0].length = 列数/行长