Returning an empty array
I'm trying to think of the best way to return an empty array, rather than null
.
Is there any difference between foo()
and bar()
?
private static File[] foo() {
return Collections.emptyList().toArray(new File[0]);
}
private static File[] bar() {
return new File[0];
}
A different way to return an empty array is to use a constant as all empty arrays of a given type are the same.
private static final File[] NO_FILES = {};
private static File[] bar(){
return NO_FILES;
}
Both foo()
and bar()
may generate warnings in some IDEs. For example, IntelliJ IDEA will generate a Allocation of zero-length array
warning.
An alternative approach is to use Apache Commons Lang 3 ArrayUtils.toArray()
function with empty arguments:
public File[] bazz() {
return ArrayUtils.toArray();
}
This approach is both performance and IDE friendly, yet requires a 3rd party dependency. However, if you already have commons-lang3 in your classpath, you could even use statically-defined empty arrays for primitive types:
public String[] bazz() {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
Definitely the second one. In the first one, you use a constant empty List<?>
and then convert it to a File[]
, which requires to create an empty File[0]
array. And that is what you do in the second one in one single step.
You can return empty array by following two ways:
If you want to return array of int
then
-
Using
{}
:int arr[] = {}; return arr;
-
Using
new int[0]
:int arr[] = new int[0]; return arr;
Same way you can return array for other datatypes as well.
return new File[0];
This is better and efficient approach.