Saturday, 20 October 2012

Collections Empty List Factory Method

You can create an empty list like so:
List<String> s = Collections.emptyList();
However, the following doesn't work:
setStrings(Collections.emptyList());
Because the compiler cannot determine what the type should be at compile time. In the first example type inference comes to the rescue. In the second example, not soo much.

What, however, does work is the following syntax I came across:
setStrings(Collections.<String> emptyList());
It's a little odd at first, but looking at the source code of emptyList() reveals:
public static final <T> List<T> emptyList() {
    return (List<T>) EMPTY_LIST;
}
The <T> in front of List<T> indicates the type that is supposed to be inferred.

Please do not use EMPTY_LIST directly, if possible. It doesn't use generics.

References

[1] Java: Collections.emptyList() returns a List<Object>?
http://stackoverflow.com/questions/306713/java-collections-emptylist-returns-a-listobject


No comments:

Post a Comment