Sometimes it is appropriate to use an immutable empty collection. The Collections
class provides methods to get such collections in an efficient way:
List<String> anEmptyList = Collections.emptyList();
Map<Integer, Date> anEmptyMap = Collections.emptyMap();
Set<Number> anEmptySet = Collections.emptySet();
These methods are generic and will automatically convert the returned collection to the type it is assigned to. That is, an invocation of e.g. emptyList()
can be assigned to any type of List
and likewise for emptySet()
and emptyMap()
.
The collections returned by these methods are immutable in that they will throw UnsupportedOperationException
if you attempt to call methods which would change their contents (add
, put
, etc.). These collections are primarily useful as substitutes for empty method results or other default values, instead of using null
or creating objects with new
.