繁体   English   中英

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

[英]Getting the array length of a 2D array in Java

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

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

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

考虑

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 中没有二维数组这样的东西。

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是(或多或少)相同的。

真的很难记住

    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 )用于列。

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

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

如果你有这个数组:

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

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

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

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

.length = 行数/列长

[0].length = 列数/行长

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

使用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:

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
 olumn_Count = arr[0].length
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();
   }  
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM