I know that similar questions have been asked several times and they were nicely answered but... they were about zero length array of 1 dimension like:
int[] array = new int[0];
Seems that there is a purpose for such arrays in case when null should not / cannot be used. But why Java allows to create things like that:
int[][][] multiDims = new int[5][0][9];
Of course like in simple 1D case we get nothing from such array if we try to iterate or something and I am asking only because it looks extremely nasty for me. :-) How much memory is allocated for such a pointless creature?
Although the size of a zero-length array is zero, an array member of this kind may increase the size of the enclosing type as a result of tail padding. The offset of a zero-length array member from the beginning of the enclosing structure is the same as the offset of an array with one or more elements of the same type.
This array is immutable (it can't be changed), and can be shared throughout the application.
Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.
As for why Java allows this - from the point of view of the language (not the concepts you're trying to express with it), why should it specifically disallow this? If you allow a zero-length array of any type, why specifically disallow a zero-length array of int[9]
? Disallowing it would necessitate more compiler checks to enforce a rule that's basically useless, because even without the rule the behavior is well defined.
Bottom line, compiler checks are not here to ensure your program makes sense. They're here only to check it's unambiguous.
Edited to add:
As pointed out in a comments, such check is not even really possible, since array length is not part of the type information and can be given at run time. So, apart of a "special case" when there's int[0]
directly in the source code, compiler doesn't even have any means to know whether it is a zero-length array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With