Collections.emptylist() returns a List<Object>
?
Collections.emptyList()
produces a type-safe List<?>
, whose generic type is inferred based on its usage context. For a specific type, you can utilize Collections.<Type>emptyList()
to explicitly denote the list's element type.
Being immutable, attempting to add an element will result in an UnsupportedOperationException.
When not given a type hint, using Collections.emptyList()
without a type parameter defaults to List<Object>
. To thwart this, either assign it to a specific type variable or use type casting.
Getting the typing right
Don't forget the type parameter
To get a typed empty list, provide a type argument:
This shows that Java infers emptyList()
as List<String>
because of the context.
Assigning emptiness
Attach it to a type variable to enforce the type:
Again, the context influences the type inference.
Calling it right
When type can't be inferred from assignment, e.g., passing emptyList()
directly to a method, be sure to invoke it with a type parameter:
Casting the emptiness
When the generic type isn't clear, you can resort to casting:
But be careful with casting, it has its quirks and may lead to a ClassCastException if not handled confessing "I'm not the object you're looking for!"
All about type inference
The type-checking conundrum
emptyList()
, when preferred without an explicit type parameter or without being assigned to a specific type variable, dresses as a List of Object or a blob of clay ready to morph:
An insight into the Matrix
Inspecting the source code explains how Collections.emptyList()
has the chameleon-like nature to return a list of any type:
The EMPTY_LIST
is a raw list that gets morphed to List<T>
during runtime.
Make use of emptyList()
In immutable collections
Being an immutable singleton instance, emptyList()
is perfect when you want a list that won't change:
With optional parameters
To avoid method duplication with optional list parameters, choose emptyList()
:
In safe-returning methods
Return emptyList()
rather than null
and leave the burden of null checks behind
EMPTY_LIST vs. emptyList(): The duel
Of Static and Generic singletons
While EMPTY_LIST
is an ageless static instance with raw power, emptyList()
is a more refined generic concoction:
Use EMPTY_LIST safely
Although tempting, overusing EMPTY_LIST
may cause unchecked warnings, emptyList()
, however, is more prudent and type-safe:
Was this article helpful?