简体   繁体   English

Java 2D Array rows vs cols 语法问题

[英]Java 2D Array rows vs cols syntax question

I am having a hard time understanding why putting brackets versus leaving them out either calls for the rows or cols in a 2D array.我很难理解为什么放置括号而不是将它们排除在外需要二维数组中的行或列。 I get the syntax I just don't understand why it works that way?我得到了我只是不明白为什么它会这样工作的语法? Should I just not worry about it and move on with my life?我应该不担心它并继续我的生活吗?

double[][] values = {
                 {1.2, 9.0, 3.2},
                 {8.2, 8.6, -1.2},
                 {-7.3, 2.5, 9.7},
                 {4.1, 7.0, 5.1},
            };
            
            System.out.println("Number of Rows: " + values.length);

            System.out.println("Number of Cols: " + values[0].length);

a 2D array is an array of arrays.二维数组是 arrays 的数组。 The variable length returns the number of elements in the array.可变length返回数组中元素的数量。

so values.length gives the number of elements in the outer array which are the inner arrays (rows)所以values.length给出了外部数组中的元素数,它们是内部 arrays (行)

and values[0].length gives the number of elements in the first inner array (columns)values[0].length给出第一个内部数组(列)中的元素数

values.length gives you the length of the outer array. values.length为您提供外部数组的长度。 That is the array containing 4 rows.那是包含 4 行的数组。 The outer array happens to contain objects that are themselves arrays.外部数组恰好包含本身是 arrays 的对象。

values[0].length gives you the length of the 1st (0th) object in the outer array. values[0].length为您提供外部数组中第一个(第 0 个)object 的长度。 This 1st object is itself an array.第一个 object 本身就是一个数组。 Since your 2D array is rectangular, every row has the same number of elements, or columns.由于您的二维数组是矩形的,因此每一行都有相同数量的元素或列。 So getting the length of any one of them will give you the number of columns因此,获取其中任何一个的长度将为您提供列数

Hope that's clearer!希望这更清楚!

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

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