Hossein Hossein - 14 days ago 11
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>


and

Collections.emptyList();


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?
thanks

Answer

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