【问题标题】:Getting the array length of a 2D array in Java在Java中获取二维数组的数组长度
【发布时间】:2011-04-29 08:21:10
【问题描述】:

我需要获取行和列的二维数组的长度。我已经成功地做到了,使用以下代码:

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。

现在看看这一行:

  int col = test[0].length;

请注意,我实际上必须引用特定行才能获得列长度。对我来说,这看起来非常丑陋。另外,如果数组被定义为:

test = new int[0][10];

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

【问题讨论】:

标签: java arrays multidimensional-array


【解决方案1】:

考虑

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
}

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

【讨论】:

  • 与您的答案无关的问题。你把“{...};”放在哪里的技术/方法是什么?在对象定义之后。作为一名新开发者,我越来越多地看到这一点。
  • 嗯,我明白了很多:)。我只是认为该技术可能有一个特定的名称。
  • 不确定它叫什么——对象初始化?内联初始化?我们的一位 Java 大师会知道
  • 根据 JLS 10.6 和 15.10,花括号部分只是一个数组初始化器,而以 new 开头的整个内容是一个数组创建表达式。
  • 另外,如果您接受二维数组作为输入,例如在构造函数中。您应该检查它并在适用的情况下抛出异常。
【解决方案2】:

二维数组不是矩形网格。或者更好的是,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));
  }
}

输出

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

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

【讨论】:

    【解决方案3】:

    真的好难记

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

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

        int[][] arr = { {1, 1, 1, 1}, 
    
                        {2, 2, 2, 2}, 
    
                        {3, 3, 3, 3} };
    

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

    【讨论】:

    • 你有这个倒退。 “在这种情况下,我们访问 [1, 1, 1, 1],因此行数 = 4。”实际上,这意味着有 4 列。
    • 正确@Evan Rosica
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      如果你有这个数组:

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

      您可以这样做:

      example.length;
      

      = 2

      example[0].length;
      

      = 2

      example[1].length;
      

      = 2

      example[0][1].length;
      

      = 3

      example[1][0].length;
      

      = 4

      【讨论】:

      • 我之前看到过类似的答案,但我认为通过示例更容易理解!
      【解决方案6】:

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

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

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

      【讨论】:

        【解决方案7】:

        .length = 行数/列长

        [0].length = 列数/行长

        【讨论】:

        • 欢迎来到 SO。您应该在答案中添加更多解释。
        【解决方案8】:

        在java中尝试以下程序来处理二维数组:

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

        【讨论】:

          【解决方案9】:
          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));   
              }
          }
          

          【讨论】:

          • 将打印 [[300.0], [600.0], [700.0], [800.0], [900.0], [1000.0]] 转换为整数以丢失小数点。此解决方案假定您的输入数组的大小始终为 ([x][1])
          【解决方案10】:

          使用Java 8,让您可以像这样做一些更优雅的事情:

          int[][] foo = new int[][] {
                  new int[] { 1, 2, 3 },
                  new int[] { 1, 2, 3, 4},
              };
          
          int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length
          

          【讨论】:

          • 1) 不同的数组名称fooarray; 2) ArrayUtils 不是标准 Java(从 Java 17 开始),请改用包 java.lang.reflect 中的 Array::getLength; 3) 可能更简单:int length =Arrays.stream(foo).mapToInt(Array::getLength).max();(不需要Comparator); 4) 不确定最大长度是否最好(用于遍历锯齿状数组时出错)
          【解决方案11】:

          示例数组 1:

          int arr[][] = { { 1, 3, 1, 5 },
                           { 2, 2, 4, 1 },
                           { 5, 0, 2, 3 },
                           { 0, 6, 1, 2 } };
          

          示例数组 2:

          int arr[][] = { { 1, 3, 1 },
                           { 2, 2, 4 },
                           { 5, 0, 2 },
                           { 0, 6, 1 } };
          

          以下函数适用于任何对称和非对称阵列矩阵

          
           row_Count = arr.length
           column_Count = arr[0].length
          
          

          【讨论】:

            【解决方案12】:
            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();
               }  
              }
            

            【讨论】:

            • 这与问题无关
            猜你喜欢
            • 2018-04-19
            • 2011-11-14
            • 2012-07-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多