Item 43: Return empty arrays or collections, not nulls

1.  It is errorprone to return null in place of an empty (zero-length) array or collection. Because the programmer writing the client might forget to write the special case code to handle a null return.

 

2.  It is possible to return the same zero-length array from every invocation that returns no items because zero-length arrays are immutable and immutable objects may be shared freely. In fact, this is exactly what happens when you use the standard idiom for dumping items from a collection into a typed array:

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

 

Collection.toArray(T[]) guarantees that the input array will be returned if it is large enough to hold the collection.

 

3.  A collection-valued method can be made to return the same immutable empty collection every time it needs to return an empty collection. The Collections.emptySet, emptyList, and emptyMap methods provide exactly what you need.

 

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

 

你可能感兴趣的:(null)