[java] 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];
}

This question is related to java arrays

The answer is


In a single line you could do:

private static File[] bar(){
    return new File[]{};
}

return new File[0];

This is better and efficient approach.


You can return empty array by following two ways:

If you want to return array of int then

  1. Using {}:

    int arr[] = {};
    return arr;
    
  2. Using new int[0]:

    int arr[] = new int[0];
    return arr;
    

Same way you can return array for other datatypes as well.


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;
}

I'm pretty sure you should go with bar(); because with foo(); it creates a List (for nothing) since you create a new File[0] in the end anyway, so why not go with directly returning it!


There is no difference except the fact that foo performs 3 visible method calls to return empty array that is anyway created while bar() just creates this array and returns it.


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.