Returning an empty array

Viewed 195771

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];
}
8 Answers

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.

return new File[0];

This is better and efficient approach.

In a single line you could do:

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