Search code examples
javacollections

Type-safe, generic, empty Collections with static generics


I return empty collections vs. null whenever possible. I switch between two methods for doing so using java.util.Collections:

return Collections.EMPTY_LIST;
return Collections.emptyList();

where emptyList() is supposed to be type-safe. But I recently discovered:

return Collections.<ComplexObject> emptyList();
return Collections.<ComplexObject> singletonList(new ComplexObject());

etc.

I see this method in Eclipse Package Explorer:

<clinit> () : void

but I don't see how this is done in the source code (1.5). How is this magic tomfoolerie happening!!

EDIT: How is the static Generic type accomplished?


Solution

  • EDIT: How is the static Generic type accomplished?

    http://www.docjar.com/html/api/java/util/Collections.java.html

    public class Collections {
        ...
        public static final List EMPTY_LIST = new EmptyList<Object>();
        ...
        public static final <T> List<T> emptyList() {
            return (List<T>) EMPTY_LIST;
        }
        ...
    }
    

    You can see the link for the implementation of the EmptyList class if you're curious, but for your question, it doesn't matter.