Item 43 - Return empty arrays or collections, not nulls

From Effective Java 2/e by Joshua Bloch

There is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection

// The right way to return an array from a collection
private final List<Cheese> cheesesInStock = ...;
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
 * @return an array containing all of the cheeses in the shop.
public Cheese[] getCheeses() {
   return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
// The right way to return a copy of a collection
public List<Cheese> getCheeseList() {
   if (cheesesInStock.isEmpty())
      return Collections.emptyList(); // Always returns same list
      return new ArrayList<Cheese>(cheesesInStock);

Returing null

  • Doing so requires extra code in the client to handle the null return value
  • It is error-prone, because the programmer writing the client might forget to write the special- case code to handle a null return
  • Returning null in place of an empty array also complicates the method that returns the array or collection

Posted by The Finest Artist