Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?
String[] strings = new String[0];
In Java program, it allows arrays of length zero. The length of the array is zero means it's an empty array. An empty array is when it contains no elements and length zero.
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.
The indexes of elements in a Java array always start with 0 and continue to the number 1 below the size of the array. Thus, in the example above with an array with 10 elements the indexes go from 0 to 9.
It signifies that it is empty. I.e. you can loop over it as if it had items and have no result occur:
for(int k = 0; k < strings.length; k++){ // something }
Thereby avoiding the need to check. If the array in question were null
, an exception would occur, but in this case it just does nothing, which may be appropriate.
Why does Java allow arrays of size 1? Isn't it pretty useless to wrap a single value in an array? Wouldn't it be sufficient if Java only allowed arrays of size 2 or greater?
Yes, we can pass null
instead of an empty array and a single object or primitive instead of a size-one-matrix.
But there are some good arguments against such an restriction. My personal top arguments:
Restriction is too complicated and not really necessary
To limit arrays to sizes [1..INTEGER.MAX_INT] we'd have to add a lot of additional boudary checks,(agree to Konrads comment) conversion logic and method overloads to our code. Excluding 0 (and maybe 1) from the allowed array sizes does not save costs, it requires additional effort and has an negative impact on performance.
Array models vector
An array is a good data model for a vector (mathematics, not the Vector
class!). And of course, a vector in mathematics may be zero dimensional. Which is conceptually different from being non-existant.
Sidenote - a prominent wrapper for an (char-)array is the String
class. The immutable String
materializes the concept of an empty array: it is the empty String (""
).
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