简体   繁体   English

字符串数组长度java

[英]String array length java

Could you tell me how to get size of reserved array ? 你能告诉我如何获取保留数组的大小吗?

Look this: 看看这个:

public static String arr_list[][][][][]= new String[2][10][10][2][5];

I know it's big array. 我知道这很重要。

I place data there, and want to get the data size of the third element. 我在此处放置数据,并希望获取第三个元素的数据大小。

arr_list[0][0].length - but it still returns 10 . arr_list[0][0].length但仍返回10

But on [0][0] I have only 4 values: 但是在[0][0]我只有4个值:

arr_list[0][0][0]..
arr_list[0][0][1]..
arr_list[0][0][2]..
arr_list[0][0][3]..

How to return 4 , not 10 ? 如何返回4 ,而不是10

Arrays are constant size containers, they always have a declared length, this is why you will always get 10. 数组是恒定大小的容器,它们始终具有声明的长度,这就是为什么您总是得到10的原因。

Consider using List s (for example ArrayList ) instead. 考虑改为使用List (例如ArrayList )。

You have initialized a 5d array..... size of 1st dimension is 2,2d is 10 3d is 10 4d is 2 and size of 5th d is 5.. 您已经初始化了5d数组.....第一维的大小是2,2d是10 3d是10 4d是2并且5th d的大小是5。

so the total size will be 2*10*10*10*2*5=20,000 if you leave them empty ..they will automatically be filled by null characters......if you want to calculate the size....you can find where the first null character is and count the elements before it 因此,如果您将其保留为空,则总大小将为2 * 10 * 10 * 10 * 2 * 5 = 20,000 ..如果要计算大小,它们将自动由空字符填充... 。您可以找到第一个空字符在哪里,并计算在其之前的元素

If you initialize an array with new String[2][10][10][2][5] you have explicitly told the system you want arr_list[0][0] to have 10 elements. 如果使用new String[2][10][10][2][5]初始化数组,则已明确告诉系统您希望arr_list [0] [0]具有10个元素。 I'm afraid it is going to believe you, and create a 10 element array. 恐怕它会相信您,并创建一个10元素数组。

If you want the size to vary depending on the number of actual element, you need to initialize it dynamically. 如果您希望大小根据实际元素的数量而变化,则需要动态初始化它。

public static String arr_list[][][][][]= new String[2][][][][]; creates arr_list with two null references of type String[][][][] . 创建具有两个String[][][][]类型的空引用的arr_list。 You can then initialize each of them with arrays containing the number of elements you actually need at the next level, and so on. 然后,您可以使用包含下一个级别实际需要的元素数量的数组来初始化它们,等等。

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

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