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]; }
Declare an empty array that has a fixed size First, we will declare an empty array with a fixed size ie 30 in this case. Next, we will not assign any value to the empty array and then we will print the output of the empty array the compiler will return a random value to avoid any runtime errors.
An empty array actually means something, as does null. To say that you should always return an empty array rather than null, is almost as misguided as saying you a boolean method should always return true. Both possible values convey a meaning. You should actually prefer returning System.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With