简体   繁体   English

在Java中,如何从大于1D的数组中获取长度值?

[英]How do you get the length value from an array greater than 1D in java?

In java, what would myArray.length be referencing in a 2D array? 在Java中, myArray.length在2D数组中将引用什么? Eg 例如

double[][] myArray = new double[3][5];

say you want to run a couple of for-loops over the array without putting the rows and columns in an argument to get hold of their value, is there a neat way to do this? 假设您要在数组上运行几个for循环,而不必将行和列放在参数中以获取其值,是否有一种巧妙的方法?

Use myArray.length and myArray[0].length . 使用myArray.lengthmyArray[0].length (This assumes that all of your "sub"-arrays are the same length.) (这假设所有“子”数组的长度都相同。)

In java, what would myArray.length be referencing in a 2D array? 在Java中,myArray.length在2D数组中将引用什么?

A 2 dimensional array of double is a 1-dimensional array or 1 dimensional array of double. double的2维数组是double的1维数组或1维数组。 myArray[0] is a an array of double ( double[] ), as is myArray[1] myArray[0]doubledouble[] )的数组, myArray[1]

So myArray.length is the number of arrays. 所以myArray.length是数组的数量。

say you want to run a couple of for-loops over the array without putting the rows and columns in an argument to get hold of their value, is there a neat way to do this? 假设您要在数组上运行几个for循环,而不必将行和列放在参数中以获取其值,是否有一种巧妙的方法?

You mean you want to access myArray[2][3] without using 3 and 4 ? 您的意思是您想不使用34来访问myArray[2][3]吗? There isn't a way to do this in Java Java无法做到这一点

As of Java 5 you can use a different looping construct, " for each ", where you avoid using array indices; 从Java 5开始,您可以使用不同的循环结构,“ for each ”,避免使用数组索引。

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

    int[][] myArray = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } };

    for ( int[] outer : myArray ) {
      for ( int inner : outer ) {
        System.out.println( inner );
      }
    }
  }
}

This prints; 这打印;

$ java Test
1
2
3
4
5
6

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

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