Prefer Collections over older classes
Avoid null if possible
Return Optional not null
NullPointerException
.
The following qualify as "empty" objects:
Example declarations of empty items:
String item = "";
BigDecimal[] items = new BigDecimal[0];
List<Integer> items = new ArrayList<>();
Map<String, Integer> items = new LinkedHashMap<>();
The Collections
class contains several type safe methods which return empty items (which are also immutable and Serializable
) :
Collections.emptyList()
Collections.emptySet()
Collections.emptyMap()
Example
Here's an example of using an empty, zero-length array instead of a null reference.
This simplifies the caller, since they never have to check for null
values.
(An even better alternative is to use replace the array with a possibly-empty collection.)
import java.util.*; public final class StockPortfolio { //..elided /** A field is implemented internally as a List, but offered to the user of this class as an Array. This array is never null, even if the underlying Collection is empty. */ public String[] getStocks() { /* NO_STOCKS plays a double role here. If there are elements in stocks, then toArray will allocate a new array, using NO_STOCKS simply as an indicator of the proper type to use. If stocks has no elements at all, then toArray will simply return the NO_STOCKS array itself. */ return stocks.toArray(NO_STOCKS); } // PRIVATE /** The underlying collection. */ private List<String> stocks; /** A constant, empty array, to be used instead of a null array. */ private static final String[] NO_STOCKS = new String[0]; }