Arrays in java are fixed in length. Why does Java allow arrays of size 0 then?
String[] strings = new String[0];
A 0-length byte[]
, or char[]
can represent an empty String
, which is distinct from null
. Getting the bytes, or characters, as arrays from strings (using getBytes()
, getChars()
of String
class etc.) and the vice-versa of forming String
s from byte[]
, char[]
is quite common. For example, for custom encoding, decoding of strings.
Sometimes it's much more friendly to return a zero size array than null.
One case I can think of where an empty array is extremely useful is to use it instead of null in a situation where null isn't allowed. One possible example of that is a BlockingQueue of arrays. When you want to signal the end of input to the reading side, what would you do? To send null seems like an obvious choice, but the thing is that BlockingQueue doesn't accept nulls. You could wrap your array inside a class with "boolean last;
" kind of field, but that's kind of overkill. Sending an empty (zero-sized) array seems like the most reasonable choice.
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.
Another case where a zero length array can be useful: To return an array containing all of the elements in a list :
<T> T[ ] toArray(T[ ] a)
A zero length array can be used to pass the type of the array into this method. For example:
ClassA[ ] result = list.toArray(new ClassA[0]);
A zero length array is still an instance of Object which holds zero elements.
Consider this (a more detailed explanation of Noon's answer):
public String[] getStrings() {
if( foo ) {
return null;
} else {
return new String[] {"bar, "baz"};
}
}
String[] strings = getStrings();
if (strings != null) {
for (String s : strings) {
blah(s);
}
}
Now compare it to this:
public String[] getStrings() {
if( foo ) {
return new String[0];
} else {
return new String[] {"bar, "baz"};
}
}
// the if block is not necessary anymore
String[] strings = getStrings();
for (String s : strings) {
blah(s);
}
This (returning empty arrays rather than null values), is in fact a best practice in Java API design world.
Besides, in Java, you can covert Lists (e.g. ArrayList) to arrays and it only makes sense to convert an empty list to an empty array.