Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java allow arrays of size 0?

Tags:

java

arrays

Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?

String[] strings = new String[0]; 
like image 275
robbin Avatar asked Jan 06 '11 06:01

robbin


People also ask

Does Java allow arrays of length zero?

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.

Can an array have a size of 0?

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.

Is an array of length 0 immutable?

This array is immutable (it can't be changed), and can be shared throughout the application.

Do arrays start at 0 or 1 Java?

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.


2 Answers

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.

like image 119
Noon Silk Avatar answered Oct 08 '22 18:10

Noon Silk


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 ("").

like image 20
Andreas Dolk Avatar answered Oct 08 '22 16:10

Andreas Dolk