Experience Directory in Software

Java,J2EE,Oracle,Linux experience and workaround tips. If you have thought at least once like "How much should I learn technologies to be good enough developer?", Yes answer is here, just read this articles.All articles are made use at real project and making clients happy!

Tuesday, October 28, 2008

Note About Item43.Return empty arrays or collections, not nulls


The note that I'd like to summarize here is about the method design in Java language and more particularly about the return value when they are either Array type or Collection objects.
It's sometimes argued that a null return value is preferable to an empty array because it avoids the expense of allocating the array.This argument fails on 2 counts.
It's 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.

For collection, use the following appropriately.

Collections.emptySet();
Collections.emptyList();
Collections.emptyMap();

for array, use the following technique.
(the following example is the case the array type is String)

private static final String[] EMPTY_STRING_ARRAY = new String[0];

Collections.toArray(EMPTY_STRING_ARRAY);

No comments:

The On Demand Global Workforce - oDesk