Hossein Hossein - 1 year ago 86
Java Question

Why would someone use Collections.emptyList in java?

Possible Duplicate:

Collections.emptyList() vs. new instance

I was trying to understand the difference between create a new instance of a list using:

new ArrayList<X>



As I understood, the later returns an immutable list. That means that it is not possible to add,delete, or modify it.
I want to know why one would create and immutable emptyList ? what is the use?

Answer Source

Say you have to return a collection and you don't want to creating a couple of objects each time.

interface Configurable {
    List<String> getConfigurationList();

// class which doesn't have any configuration
class SimpleConfigurable implements Configurable {
    public List<String> getConfigurationList() { return Collections.emptyList(); }

Returning an empty collection is often preferable to returning null

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download