Java中的多维数组长度 [英] Multidimensional Arrays lengths in Java

查看:31
本文介绍了Java中的多维数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何求索引不等的多维数组的长度?

How to find the lengths of a multidimensional array with non equal indices?

例如,我有 int[][] pathList = new int[6][4]

实际上没有对索引进行硬编码,我需要找到6"和4".

Without actually hard-coding the indices, I need to find the '6' and the '4'.

我可以用 pathList.length 找到 6,但是如何获得 '4'?

I can find the 6 with pathList.length, but how to obtain the '4'?

推荐答案

这会给你在索引 i

pathList[i].length

需要注意的是,与 C 或 C++ 不同,Java 中二维数组的元素长度不必相等.例如,当pathList被实例化等于new int[6][]时,它可以容纳6个int []实例,每个实例可以是不同的长度.

It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.

因此,当您按照问题中显示的方式创建数组时,您也可以这样做

So when you create arrays the way you've shown in your question, you may as well do

 pathList[0].length

因为你知道它们都具有相同的长度.在其他情况下,您需要针对您的应用程序精确定义什么第二维的长度意味着 - 它可能是所有元素长度的最大值,或者可能是最小值.在大多数情况下,您需要遍历所有元素并阅读它们的长度以做出决定:

since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:

for(int i = 0; i < pathList.length; i++)
{
    int currLen = pathList[i].length;
}

这篇关于Java中的多维数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆