For example we can construct such an array like this:
new ElementType[0];
I seen such a construct, but I don\'t understand why this might
It's easier to work with than null
in many cases, where null
is the obvious alternative.
Suppose you want to return an Iterable<String>
containing (say) a list of relevant filenames... but there aren't any for some reason. You could return null
to indicate that, but then the caller has to special-case that. Instead, if you return an empty collection, the caller can still use an enhanced for loop:
for (String file : getFiles())
So why use an empty array instead of an empty ArrayList
or something similar? Arrays are a fixed size, so an empty array is effectively immutable. That means you can keep a single value and return it to whoever you like, knowing they can't possibly do anything with it. That can be very useful in some situations.
it is a replacement for null since you don't need to check for null before use it. More formally it is a special case of special case design pattern (check also Null Object).
Another idiomatic use is collections toArray:
List<String> list = new ... ;
// fill the list
String[] array = list.toArray(new String[0]);
An example. Say, you have a function
public String[] getFileNames(String criteria) {
to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.
The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).
There's a chapter on this in Effective Java, Item 27