Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an empty array

Tags:

java

arrays

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]; } 
like image 581
Moonbeam Avatar asked Jul 21 '11 18:07

Moonbeam


People also ask

How do you return an empty array in C++?

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.

Should I return null or empty array?

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.


2 Answers

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; } 
like image 195
Peter Lawrey Avatar answered Sep 24 '22 14:09

Peter Lawrey


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; } 
like image 31
weekens Avatar answered Sep 24 '22 14:09

weekens