简体   繁体   中英

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 .

But on [0][0] I have only 4 values:

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 ?

Arrays are constant size containers, they always have a declared length, this is why you will always get 10.

Consider using List s (for example ArrayList ) instead.

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..

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

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. I'm afraid it is going to believe you, and create a 10 element array.

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[][][][] . You can then initialize each of them with arrays containing the number of elements you actually need at the next level, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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