Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?
String[] strings = new String[0];
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 (""
).